I'm trying to create a simple bash script but I can't get the variable handling right. When the RESULT variable receives an empty value it does not echo "-1", it returns a 0. Why does bash turn the empty value into 0?
SERVICE="$1"
RESULT=`ps auxw | grep ${SERVICE} | grep -v grep | awk '{s+=$3} END {print s}'`
if [ -z "$RESULT" ]; then
echo "-1"
else
echo $RESULT
fi
bash -x
orset -x
and see what's happening.pgrep
.V=$(some cmd); if test -z "$V" ...
. In your case, just do:ps auxw | ... | grep -q . || echo -1
. That is, let the command write its output togrep -q .
. If no output is generated, echo -1. You might want to consider not usingps auxw
here, and you might consider writing that -1 to stderr.