Bash变量在for循环中重置(无管道)
我已经将代码缩减到这个简单的for循环。我不明白为什么计数器tot_add不是累积的,而是始终为1:Bash变量在for循环中重置(无管道),bash,Bash,我已经将代码缩减到这个简单的for循环。我不明白为什么计数器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 预期结果: 1 2 3 实际结果 1 1 1 我读过这个关于带管道的地下室的答案 但是,我在这里没有使用管道字符。()生成子shell 因此,它实际上被添加到子she
cd /path/to/my/workspace;
tot_add=0;
for d in ./*/;
do (cd "$d";
let tot_add=tot_add+1;
echo $tot_add;
) done
预期结果:
1
2
3
实际结果
1
1
1
我读过这个关于带管道的地下室的答案
但是,我在这里没有使用管道字符。()
生成子shell
因此,它实际上被添加到子shell中,当子shell退出时,父shell没有结果,而是从0
重新开始,因此总是得到1
要修复此行为,请清除子shell。您正在使用(
…)
。这显式地创建了一个子shell。