0

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
  • Run your script with bash -x or set -x and see what's happening. – muru Jun 11 at 13:55
  • I tried your script and it works, what is the issue? – coffeMug Jun 11 at 13:56
  • This would be better handled using pgrep. – Kusalananda Jun 11 at 14:37
  • There's really never a need to use the pattern 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 to grep -q . . If no output is generated, echo -1. You might want to consider not using ps auxw here, and you might consider writing that -1 to stderr. – William Pursell Jun 11 at 15:27
3

Because there is always a ${RESULT}. You see, you put the ${SERVICE} in the command line when you search for it so its always found. See how can we avoid it:

cat search.sh

SERVICE="$1"
RESULT=$(ps auxw | grep ${SERVICE} | grep -v 'grep\|search.sh' | awk '{s+=$3} END {print s}')
if [ -z "$RESULT" ]; then
   echo "-1"
else
   echo $RESULT
fi

I added the name of the script into the grep -v. Otherwise there is always a process called search.sh ${SERVICE}

However it is far from best practice. As I understand, you need the current CPU usage of the process by name? Consider the following:

SERVICE="$1"
RESULT=`pgrep ${SERVICE}`
if [ -z "$RESULT" ]; then
   echo "-1"
else
   for proc in ${RESULT}; do ps -p ${proc} -o %cpu | tail -n +2; done
fi
  • Thanks for the help! This script works as expected :) – Cmits Jun 12 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.