2013-07-18 107 views
0

我寫git的鉤和下一個代碼的行爲很困惑:使用SH而讀線循環迭代計數器外循環

#!/bin/sh 

exit_code=0 

git diff --cached --name-only --diff-filter=ACM | while read line; do 
    echo "Do something with file: $line" 
    # some stuff with exit code is equals to 0 or 1 
    stuff_exit_code=$? 
    exit_code=$(($exit_code + $stuff_exit_code)) 
done 

echo $exit_code 
exit $exit_code 

我希望回聲$ exit_code會產生文件總量對於我的東西退出代碼是非零。但我總是看到0.我的錯誤在哪裏?

回答

0

這是因爲管道在不同的過程中執行。剛將其替換爲for-in循環。

#!/bin/sh 

exit_code=0 

for file in `git diff --cached --name-only --diff-filter=ACM` 
do 
    echo "Do something with file: $file" 
    # some stuff with exit code is equals to 0 or 1 
    stuff_exit_code=$? 
    exit_code=$(($exit_code + $stuff_exit_code)) 
done 

echo $exit_code 
exit $exit_code