2

i found some freaky error. I want to increment a counter, but the variable isnt visible outside the while do.

The script as follows:

    ## $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

So i dont know what else to try. Thanks in advance.

1

4 Answers 4

2

The problem is that pipe create a SubShell.

change

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

to

while read line
do
    ...
done <(cat $1 | grep "$3")
Sign up to request clarification or add additional context in comments.

Comments

1

As noted, the Bash shell, creates a subshell whenever a pipe is opened to a loop. In that case, variables within the loop are local to the loop.

One kludge is to substitute (if possible) a Korn ('ksh') shell for the Bash one.

1 Comment

I'd argue that this is not a kludge, and is in fact one of the key strengths of ksh for shell programming
0

Try something like:

## $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

Comments

0

while is executed in a separate process. Variables that are changed in the context of that process still hold their unchanged valus in the parent process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.