2011-12-12 60 views
2

我發現了一些奇怪的錯誤。我想增加一個計數器,但這個變量不是在可見的範圍之外。錯誤與殼腳本

如下腳本:

## $1 - The file which should be examined 
## $2 - The time passed between the checks. If $2 is 5 then all lines from the last 5 minutes are taken 
## $3 - The Errormessage to search for 

outputOK="OK - nothing happened" 
output_logcheck=0; 
errlines=""; 

cat $1 | grep "$3" | while read line 
do 
     linedate=`date -d "$(echo $line | cut -d " " -f 2)" '+%s'` 
     nowdate=`date '+%s'` 

     if [ $(($nowdate - (60 * $2))) -le $linedate ] 
     then 
       $output_logcheck=$[$output_logcheck+1] 
       $errlines="${errlines} -- ${line}" 
     fi 
done; 

if [ $output_logcheck -eq 0 ] 
then 
     echo $outputOK 
else 
     echo "CRITICAL - There are -= ${output_logcheck} =- $3 -- Lines: $errlines" 
fi 

所以我不知道什麼嘗試。 在此先感謝。

+1

有關於這個問題的常見問題解答條目,僅供將來參考:[「我在流水線中的循環中設置變量,爲什麼在循環終止後它們消失?或者,爲什麼我不能讀取數據以讀取?「](http://mywiki.wooledge.org/BashFAQ/024) –

回答

2

問題是pipe創建SubShell

變化

cat $1 | grep "$3" | while read line 
do 
    ... 
done 

while read line 
do 
    ... 
done <(cat $1 | grep "$3") 
0

嘗試類似:

## $1 - The file which should be examined 
## $2 - The time passed between the checks. If $2 is 5 then all lines from the last 5 minutes are taken 
## $3 - The Errormessage to search for 

outputOK="OK - nothing happened" 
outfile="/tmp/result.$$" 

trap { rm $outfile } 0 1 2 3 

cat $1 | grep "$3" | (output_logcheck=0; errlines=""; while read line 
do 
     linedate=`date -d "$(echo $line | cut -d " " -f 2)" '+%s'` 
     nowdate=`date '+%s'` 

     if [ $(($nowdate - (60 * $2))) -le $linedate ] 
     then 
       $output_logcheck=$[$output_logcheck+1] 
       $errlines="${errlines} -- ${line}" 
     fi 
done; echo $output_logcheck ":" $errlines > $outfile) 

output_logcheck=`cat $outfile| cut -f1 -d:` 
errlines=`cat $outfile|cut -f2 -d:` 

if [ $output_logcheck -eq 0 ] 
then 
     echo $outputOK 
else 
     echo "CRITICAL - There are -= ${output_logcheck} =- $3 -- Lines: $errlines" 
fi 
0

while是在一個單獨的進程中執行。在該過程中更改的變量在父進程中仍保持不變。

1

如指出的,擊殼,創建每當管打開至環子shell。在這種情況下,循環內的變量對於循環來說是局部的。

一個kludge將替換(如果可能)一個Korn('ksh')shell爲Bash一個。

+0

我認爲這不是一團糟,實際上是ksh for shell編程的關鍵優勢之一 –