Andy
Andy

Reputation: 588

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

Upvotes: 7

Views: 24630

Answers (3)

Roman Cheplyaka
Roman Cheplyaka

Reputation: 38718

How about

pgrep -c sms_queue

?

And the whole (portable) version of the script would look like this:

if [ "$(pgrep -c sms_queue)" -le 15 ]; then
  echo "Done."
else
  echo "Not Complete."
fi

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881373

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.

Upvotes: 19

MForster
MForster

Reputation: 9376

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

variable=$(my command)

Upvotes: 1

Related Questions