[bash] How to check if a process id (PID) exists

In a bash script, I want to do the following (in pseudo-code):

if [ a process exists with $PID ]; then

    kill $PID 

fi

What's the appropriate expression for the conditional statement?

This question is related to bash process pid

The answer is


You have two ways:

Lets start by looking for a specific application in my laptop:

[root@pinky:~]# ps fax | grep mozilla
 3358 ?        S      0:00  \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2    S+     0:00              \_ grep mozilla

All examples now will look for PID 3358.

First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:

[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358

So your code will be:

if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
    kill $PID 
fi

Second way: Just look for something in the /proc/$PID directory. I am using "exe" in this example, but you can use anything else.

[root@pinky:~]# ls -l /proc/3358/exe 
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash

So your code will be:

if [ -f /proc/$PID/exe ]; then
    kill $PID 
fi

BTW: whats wrong with kill -9 $PID || true ?


EDIT:

After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.


I think that is a bad solution, that opens up for race conditions. What if the process dies between your test and your call to kill? Then kill will fail. So why not just try the kill in all cases, and check its return value to find out how it went?


It seems like you want

wait $PID

which will return when $pid finishes.

Otherwise you can use

ps -p $PID

to check if the process is still alive (this is more effective than kill -0 $pid because it will work even if you don't own the pid).


The best way is:

if ps -p $PID > /dev/null
then
   echo "$PID is running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
fi

The problem with:

kill -0 $PID

is the exit code will be non-zero even if the pid is running and you dont have permission to kill it. For example:

kill -0 1

and

kill -0 $non-running-pid

have an indistinguishable (non-zero) exit code for a normal user, but the init process (PID 1) is certainly running.

DISCUSSION

The answers discussing kill and race conditions are exactly right if the body of the test is a "kill". I came looking for the general "how do you test for a PID existence in bash".

The /proc method is interesting, but in some sense breaks the spirit of the "ps" command abstraction, i.e. you dont need to go looking in /proc because what if Linus decides to call the "exe" file something else?


here i store the PID in a file called .pid (which is kind of like /run/...) and only execute the script if not already being executed.

#!/bin/bash
if [ -f .pid ]; then
  read pid < .pid
  echo $pid
  ps -p $pid > /dev/null
  r=$?
  if [ $r -eq 0 ]; then
    echo "$pid is currently running, not executing $0 twice, exiting now..."
    exit 1
  fi
fi

echo $$ > .pid

# do things here

rm .pid

note: there is a race condition as it does not check how that pid is called. if the system is rebooted and .pid exists but is used by a different application this might lead 'unforeseen consequences'.


if [ -n "$PID" -a -e /proc/$PID ]; then
    echo "process exists"
fi

or

if [ -n "$(ps -p $PID -o pid=)" ]

In the latter form, -o pid= is an output format to display only the process ID column with no header. The quotes are necessary for non-empty string operator -n to give valid result.


By pid:

pgrep [pid] >/dev/null

By name:

pgrep -u [user] -x [name] >/dev/null

"-x" means "exact match".


ps command with -p $PID can do this:

$ ps -p 3531
  PID TTY          TIME CMD
 3531 ?        00:03:07 emacs

For example in GNU/Linux you can use:

Pid=$(pidof `process_name`)

if [ $Pid > 0 ]; then

   do something
else

   do something
fi 

Or something like

Pin=$(ps -A | grep name | awk 'print $4}')
echo $PIN

and that shows you the name of the app, just the name without ID.


Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to process

Fork() function in C How to kill a nodejs process in Linux? Xcode process launch failed: Security Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes Linux Script to check if process is running and act on the result CreateProcess error=2, The system cannot find the file specified How to make parent wait for all child processes to finish? How to use [DllImport("")] in C#? Visual Studio "Could not copy" .... during build How to terminate process from Python using pid?

Examples related to pid

How to get PID by process name? Why is $$ returning the same id as the parent process? How to get PID of process by specifying process name and store it in a variable to use further? ERROR! MySQL manager or server PID file could not be found! QNAP How to get the PID of a process by giving the process name in Mac OS X ? Determine the process pid listening on a certain port What is a .pid file and what does it contain? How to get PID of process I've just started within java program? How to check if a process id (PID) exists How does a Linux/Unix Bash script know its own PID?