Is it possible to make the variable inside nested for loop local
Is it possible to make the variable inside nested for loop local.
Yes, but only using a function.
As the builtin local
can only exist inside a function, we need to provide a function to make the variable i
change the scope from global to local:
#!/bin/bash
internalfunction () {
local i ### Works as is inside a function
for i in 1 2 3; do
echo "inner loop ----- $i"
(( i++ ))
done
}
for i in 1 2 3 4; do
echo $i
internalfunction
done
$ ./script.sh
1
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
2
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
3
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
4
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
If you run the inner variable in a sub shell, it will not affect the outer variable:
for i in 1 2 3 4; do
(
for i in 1 2 3; do
echo "inner loop ----- $i"
(( i++ ))
done
)
echo $i
done
Which results in:
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
1
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
2
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
3
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
4