Bash shell脚本错误
我发现了一些奇怪的错误。我想增加一个计数器,但变量在whiledo之外不可见 脚本如下:Bash shell脚本错误,bash,variables,global-variables,Bash,Variables,Global Variables,我发现了一些奇怪的错误。我想增加一个计数器,但变量在whiledo之外不可见 脚本如下: ## $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 -
## $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 - 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
而
在单独的进程中执行。在该进程的上下文中更改的变量在父进程中仍然保持其不变的值。问题在于管道
创建子shell
改变
cat $1 | grep "$3" | while read line
do
...
done
到
读取行时
做
...
done如前所述,每当管道打开到循环时,Bash shell就会创建一个子shell。在这种情况下,循环中的变量是循环的局部变量
一个难题是(如果可能的话)用Korn(“ksh”)shell替换Bash shell。关于这个问题有一个FAQ条目,仅供将来参考:我认为这不是一个难题,事实上是ksh在shell编程方面的关键优势之一
while read line
do
...
done <(cat $1 | grep "$3")