2011-12-12 59 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编程的关键优势之一 –