2016-11-25 55 views
0

我的bash版本是GNU bash,版本4.3.42(1)-release(x86_64-pc-linux-gnu)。這是我的腳本的簡化版本:由於範圍在bash中可變的丟失值

#!/bin/bash 
touch a.ecl 
touch b.ecl 

function_syntaxCheckFileName() 
{ 
    return 1 # 1 syntax error 
} 

tmpTotalErrors=0 
result=0 
echo "DEBUG Starting loop" 
find . -name '*.ecl' -print0 | while read -d $'\0' file 
do 
    echo " DEBUG - FILE=$file" 
    echo " DEBUG0 tmpTotalErrors=$tmpTotalErrors --- result=$result" 
    function_syntaxCheckFileName "$file" 
    result=$? 
    echo " DEBUG1 tmpTotalErrors=$tmpTotalErrors --- result=$result" 
    tmpTotalErrors=$((tmpTotalErrors + result)) 
    echo " DEBUG2 tmpTotalErrors=$tmpTotalErrors --- result=$result" 
done 

echo "DEBUG3 tmpTotalErrors=$tmpTotalErrors" 

它的設計路徑用空格來運行,所以我用這個迭代

發現。 -name'* .ecl'-print0 |而讀-d $ '\ 0' 文件

輸出是這樣的:

DEBUG Starting loop 
DEBUG - FILE=./a.ecl 
    DEBUG0 tmpTotalErrors=0 --- result=0 
    DEBUG1 tmpTotalErrors=0 --- result=1 
    DEBUG2 tmpTotalErrors=1 --- result=1 
DEBUG - FILE=./b.ecl 
    DEBUG0 tmpTotalErrors=1 --- result=1 
    DEBUG1 tmpTotalErrors=1 --- result=1 
    DEBUG2 tmpTotalErrors=2 --- result=1 
DEBUG3 tmpTotalErrors=0 

問題是tmpTotalErrors失去其價值。它應該是2,這是0

所以我問題是:

  1. 我哪有我的腳本工作?
  2. 爲什麼失敗?

回答

3

重寫循環以避免subshel​​使用set + m;禁用了javascript -s lastpipe

#!/bin/bash 
set +m 
shopt -s lastpipe 
touch a.ecl 
touch b.ecl 

function_syntaxCheckFileName() 
{ 
    return 1 # 1 syntax error 
} 

tmpTotalErrors=0 
result=0 
echo "DEBUG Starting loop" 

find . -name '*.ecl' -print0 | while read -d $'\0' file 
do 
    echo " DEBUG - FILE=$file" 
    echo " DEBUG0 tmpTotalErrors=$tmpTotalErrors --- result=$result" 
    function_syntaxCheckFileName "$file" 
    result=$? 
    echo " DEBUG1 tmpTotalErrors=$tmpTotalErrors --- result=$result" 
    tmpTotalErrors=$((tmpTotalErrors + result)) 
    echo " DEBUG2 tmpTotalErrors=$tmpTotalErrors --- result=$result" 
done 
echo "DEBUG3 tmpTotalErrors=$tmpTotalErrors" 

它的失敗,因爲在subshell變化不會在父shell反映。

另請參閱此Bash FAQ條目:I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?,其中討論了一些替代解決方案。

+0

我試過你的代碼,它沒有進入循環。輸出是'DEBUG開始循環 DEBUG3 tmpTotalErrors = 0' –

+0

@OscarFoley:將'read'更改爲'read -r -d'' – Inian

+0

更改結果相同。我的行現在是'while read -r -d''file'你能更新你的答案嗎? –