15
#!/bin/bash
for i in  1 2 3 4
do

#   {
#   local i     ##gives error  local: can only be used in a function
    for i in 1 2 3
    do
    echo "inner loop ----- $i"
    (( i++ ))
    done
#   }
echo $i
done

outout :

inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
4
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
4
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
4
inner loop ----- 1
inner loop ----- 2
inner loop ----- 3
4

Is it possible to make the variable inside nested for loop local.

2 Answers 2

16

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
3
  • 2
    Also valid, and much easier to read.
    – coteyr
    May 16, 2016 at 4:00
  • just noticed that using just { } makes the variables local.declareing the var using declare also makes it local
    – munish
    May 17, 2016 at 5:41
  • 2
    @munish No, only { } is not enough. Yes, declare makes a var local Inside a function.
    – user79743
    May 17, 2016 at 6:29
12

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
3
  • 2
    This is valid, but please don't. It makes this much harder to read at a glance.
    – coteyr
    May 16, 2016 at 3:59
  • 1
    Abusing subshells too much could make a script noticeably slower.
    – user23013
    May 16, 2016 at 5:51
  • 3
    But it is harder to read only to those people who don't abuse subshells.
    – user23013
    May 16, 2016 at 5:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .