Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script with basic if/else and count of processes running based on a pattern

I'm trying to write a script that counts the number of processes running matching a patern. If it exceeds a hardcoded value then do something...else do something else.

I am finding out the count of processes using:

ps ax | grep process_name | wc -l | sed -e "s: ::g"

If the output of the above command is greater than 15..it should echo "Done". Otherwise, echo "Not Complete".

So far, I have this but it isn't working:

numprocesses=ps ax | grep sms_queue | wc -l | sed -e "s: ::g"
if [ $numprocesses -le "15" ] ; then
  echo "Done."
else
  echo "Not Complete."
fi
like image 555
Andy Avatar asked Nov 05 '10 06:11

Andy


2 Answers

numprocesses=$(ps ax | grep '[s]ms_queue' | wc -l)
if [[ $numprocesses -gt 15 ]] ; then
  echo "Done."
else
  echo "Not Complete."
fi

You had a few problems.

  • Your if statement didn't quite match your specification.
  • To capture the output of the xyz command, you should use $(xyz).
  • No need for stripping spaces from the output.
  • If you don't want to pick up the grep process as well (because it too has the pattern it's looking for), you should use the [firstchar]rest grep pattern (or you can use | grep sms_queue | grep -v grep to remove the grep process from the count as well.
  • no need to use the string "15" in the comparison.
like image 83
paxdiablo Avatar answered Oct 12 '22 21:10

paxdiablo


If you want to copy the output of a command into a variable use this syntax:

variable=$(my command)
like image 29
MForster Avatar answered Oct 12 '22 22:10

MForster