Check if the process is running.

I am trying to check if a process is running. If it works, I want to get the return value "OK", and if I do not return the value "Out of Order". I can use "ps" without any other arguments (for example, ps -ef) if that is the correct term. The code I have is:

if ps | grep file; then echo 'OK'; else echo 'NO'; fi 

The problem is that it does not search for the exact process and always returns “OK”, I do not want all the information to be displayed. I just want to know if the file exists.

+6
linux bash grep process
source share
7 answers

Your code always returns “OK” because grep is in the list of processes (“grep file” contains the word “file”). A fix would be to run the command grep -e [f] ile '(-e for regex), which does not find itself.

+10
source share

Stock grep for real tasks:

 ps -C file 

avoids the problem of using grep in general.

+6
source share
 ps | grep -q '[f]ile' 
+2
source share

When I know pid, I prefer:

 [ -d /proc/<pid> ] && echo OK || echo NO 
+1
source share

How about pgrep?

 $ pgrep -x foo xxxx $ 

where xxxx is the pid of the binary run named foo. If foo does not work, then there is no output.

also:

$ if [[ pgrep -x foo ]]; then the echo yes; else echo "no"; Fi

will print yes if foo is running; no if not.

see the pgrep man page.

+1
source share
 if ps | grep file | grep -v grep; then echo 'ok'; else echo 'no'; 

grep -v grep ensures that the result is not a grep expression when executed.

0
source share

There is also a solution with grep:

 if [ "$(ps aux | grep "what you need" | awk '{print $11}')" == "grep" ]; then ... elif [ ... ]; then ... else ... fi 

This works fine in Debian 6, but is not sure about other distributions. '{print $11}' because the system treats grep as a process.

-one
source share

All Articles