I have the command:
ps ax | grep my_application
Which outputs a large string including the port of the proccesses involved in my_application.
If my_application is not running it outputs:
3873 pts/0 S+ 0:00 grep my_application
I need a condition to test the output of ps ax | grep my_application
and do exit 2
in case my_application is still running.
Any ideas?
You can add brackets to exclude the grep process:
ps ax | grep -q '[m]y_application' && exit 2
If my_application is running, ps ax
will print my_application along with the grep command and pattern. Grep understands [m]
as a character class, but it will not match the litteral string '[m]'
printed by ps ax
, so the grep process is excluded.
The simplest solution is to use pgrep
, if it is available on your system.
Otherwise, you can customize the way ps
reports processes. You don't have to use the default format, which includes (some) command-line arguments.
For example:
ps ax -ocomm
will only output the executable name. If you want pids as well,
ps ax -opid,comm
For convenient grepping, you might want to remove the headers
ps ax -opid=,comm=
Any of those should work just fine as input to grep application_name
, although you still need to watch out for application_name
being a substring of another application name.
man ps
should give you the list of possible output fields. There are lots of them.
You can exclude stuff from the results returned by grep by using something like this:
ps ax | grep my_application | grep -v grep
This excludes the process that is returning when your application is not running that shows the grep running. When this is run and your application is not running, it will return nothing. Check for the empty string, and exit that way.