简体   繁体   English

Bash变量在for循环中重置(无管道)

[英]Bash variable resets in for loop (no pipe)

I have trim down my code to this simple for loop. 我已经将代码精简为这个简单的for循环。 I don't understand why the counter tot_add is not cumulative but rather 1 all the time: 我不明白为什么计数器tot_add不是一直累加而是1:

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. 我已经阅读了有关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?" BASH常见问题解答条目24:“我在循环中设置了变量。为什么循环终止后它们突然消失?或者,为什么我不能通过管道传输要读取的数据?”

However, I'm not using pipe character here. 但是,我在这里不使用竖线字符。

() spawns a subshell. ()产生一个subshel​​l。

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. 因此,它实际上是添加到子shell中的,当子shell退出时,父shell没有结果,而是从0开始,因此您总是得到1。

To fix this behavior, get rid of the subshell. 若要解决此问题,请摆脱子外壳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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