2016-06-25 38 views
1

我已經將我的代碼修剪到這個簡單的for循環。我不明白爲什麼反tot_add不具有累積性,而是1所有的時間:Bash變量重置爲for循環(無管道)

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 

我看了這個答案關於Pipe的子shell。

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?"

不過,我沒有使用管道字符在這裏。

+1

您正在使用'('...')'。這明確地創建了一個子shell。 – melpomene

回答

2

()衍生出一個子殼。

因此,在一個子shell被實際添加並在子shell退出父shell沒有得到的,而從0再次啓動,因此你總是越來越1.

要解決此問題,擺脫子外殼。