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
4
  • Run your script with bash -x or set -x and see what's happening.
    – muru
    Commented Jun 11, 2019 at 13:55
  • I tried your script and it works, what is the issue?
    – Vombat
    Commented Jun 11, 2019 at 13:56
  • This would be better handled using pgrep.
    – Kusalananda
    Commented Jun 11, 2019 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. Commented Jun 11, 2019 at 15:27

1 Answer 1

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
1
  • Thanks for the help! This script works as expected :)
    – Cmits
    Commented Jun 12, 2019 at 19:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .