Check if program is running script using ps aux & grep

bbot
Contributor

I'm writing a script to update an application and am running into something strange with ps aux.
If I run the processNum variable locally without the application open, it returns 1.
If I run the processNum variable through the script without the application open, it returns 4

If I run the processNum variable locally with the application open, it returns 3
If I run the processNum variable through the script with the application open, it returns 6.

Does anyone know why it appears to be adding 3 to the value when being run as a bash script? See below for what I'm doing.

processNum=$(ps aux | grep "Jabber" | wc -l)
       # If Jabber is not open, remove and install new version
        if [ $processNum -lt 5 ]; then 
                rm -rf /Applications/Cisco Jabber.app
                /usr/local/jamf/bin/jamf policy -trigger customtriggerhere
else
 echo "hi"
1 REPLY 1

leungn
New Contributor II

@bbot You can probably debug this yourself by stepping back through the processNum variable.
To get you started:
>> If I run the processNum variable locally without the application open, it returns 1.
This is returning 1 since grep is matching against the pattern you requested with the grep process. It sees itself:

$ ps aux | grep "Jabber"
22920 s000  S+     0:00.00 grep "Jabber"

Adding the wc -l will give you 1, since it's one line returned. You can work around this by filtering out grep with another grep:

ps aux | grep "Jabber" | grep -v "grep"

or use a pattern with a set as a workaround:

ps aux | grep "[J]abber"

The latter works since "Jabber" does not match "[J]abber" in the grep process.

A few more tips:
1. Since you don't really care which user owns the process, omit the 'u' in the ps call. This reduces clutter. Simplify to:

ps ax

2. You can be more specific in your grep pattern match. This can reduce 'by-catch':

grep "Cisco Jabber.app"

3. You are probably more concerned with the number of occurrences of 'Cisco Jabber.app'. So let's cut out the middle man (wc), and ask grep for the count.

grep -c "Cisco Jabber.app"

In summary, try this:

ps ax | grep -c "[C]isco Jabber.app"