2013-12-15 48 views
1

我試圖計算每行包含一個單詞的文件中的單詞出現(使用egrep被禁止)。我設法找到了解決方案,但是我偶然發現了一件非常奇怪的事情,我想解釋一下爲什麼會發生這種情況。Shell - 循環後變量丟失值

我的「count」變量在循環後的值爲0,但在循環過程中它會正確遞增。

這裏是我的代碼:

for var in "[email protected]" 
do 
    count=0 
    cat $1 | while read line ; do 
     if [ $line = $var ]; then 
      count=$((count + 1)) 
      echo "$var found $count times" 
     fi 
    done  
    echo $count 
done 

我的輸出是:

yes found 0 times 
yes found 1 times 
yes found 2 times 
0 - This is from the echo $count, which I find it very odd to be zero, since it got incremented to 3 during the loop. 

回答

1

我相信,當你用管道輸送新的子殼被啓動,並計數在外殼不是您當前正在修改。好像其他人也有這個問題。我遇到了另一個Thread的解決方案。我希望這有幫助!