Please explain to me why the very last "echo" statement is blank? I expect that it was incremented in the while loop to a value of 1:
#!/bin/bash
OUTPUT="name1 ip ip status" # normally output of another command with multi line output
if [ -z "$OUTPUT" ]
then
echo "Status WARN: No messages from SMcli"
exit $STATE_WARNING
else
echo "$OUTPUT"|while read NAME IP1 IP2 STATUS
do
if [ "$STATUS" != "Optimal" ]
then
echo "CRIT: $NAME - $STATUS"
echo $((++XCODE))
else
echo "OK: $NAME - $STATUS"
fi
done
fi
echo $XCODE
I've tried using the following statement instead of the ++XCODE method
XCODE=`expr $XCODE + 1`
and it too wont print outside of the while statement. I think I'm missing something about variable scope here but the ol' man page isnt showing it to me.
One more option:
EDIT: Here, xsel is a requirement (install it). Alternatively, you can use xclip:
xclip -i -selection clipboard
instead ofxsel -i -p
I got around this when I was making my own little du:
The point is that I make a subshell with ( ) containing my SUM variable and the while, but I pipe into the whole ( ) instead of into the while itself, which avoids the gotcha.
see if those changes help
Because you're piping into the while loop, a sub shell is created to run the while loop. Now this child process has it's own copy of the environment and can't pass any variables back to its parent (as in any unix process).
Therefore you'll need to restructure so that you're not piping into the loop. Alternatively you could run in a function for example and echo the value you want returned from the sub process.
http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL
This should work as well (because echo and while are in same subshell):
Another option is to output the results into a file from the subshell and then read it in the parent shell. something like