How to test if a process is running with grep in b

2019-07-16 23:21发布

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 2in case my_application is still running.

Any ideas?

标签: linux bash shell
3条回答
2楼-- · 2019-07-16 23:48

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-16 23:49

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.

查看更多
做自己的国王
4楼-- · 2019-07-16 23:55

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.

查看更多
登录 后发表回答