简体   繁体   中英

Bash variable resets in for loop (no pipe)

I have trim down my code to this simple for loop. I don't understand why the counter tot_add is not cumulative but rather 1 all the time:

cd /path/to/my/workspace;
tot_add=0;
for d in ./*/;
do (cd "$d";
 let tot_add=tot_add+1;
 echo $tot_add;
) done

expected result:

1
2
3

actual result

1
1
1

I have read this answer about subshell with Pipe.

BASH FAQ entry #24: "I set variables in a loop. Why do they suddenly disappear after the loop terminates? Or, why can't I pipe data to read?"

However, I'm not using pipe character here.

() spawns a subshell.

So it being actually added in a subshell and when the subshell exits the parent shell does not have the resultant rather starts again from 0 , hence you are always getting 1.

To fix this behavior, get rid of the subshell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM