How to determine whether a process is running or not and make use it to make a conditional shell script?
How can I determine if a process is running or not and then have a bash script execute some stuff based on that condition?
For example:
if process
abc
is running, do thisif it is not running, do that.
Solution 1:
A bash script to do something like that would look something like this:
#!/bin/bash
# Check if gedit is running
# -x flag only match processes whose name (or command line if -f is
# specified) exactly match the pattern.
if pgrep -x "gedit" > /dev/null
then
echo "Running"
else
echo "Stopped"
fi
This script is just checking to see if the program "gedit" is running.
Or you can only check if the program is not running like this:
if ! pgrep -x "gedit" > /dev/null
then
echo "Stopped"
fi
Solution 2:
Any solution that uses something like ps aux | grep abc
or pgrep abc
are flawed.
Why?
Because you are not checking if a specific process is running, you are checking if there are any processes running that happens to match abc
. Any user can easily create and run an executable named abc
(or that contains abc
somewhere in its name or arguments), causing a false positive for your test. There are various options you can apply to ps
, grep
and pgrep
to narrow the search, but you still won't get a reliable test.
So how do I reliably test for a certain running process?
That depends on what you need the test for.
I want to ensure that service abc is running, and if not, start it
This is what systemd is for. It can start the service automatically and keep track of it, and it can react when it dies.
See How can I check to see if my game server is still running... for other solutions.
abc is my script. I need to make sure only one instance of my script is running.
In this case, use a lockfile or a lockdir. E.g.
#!/usr/bin/env bash
if ! mkdir /tmp/abc.lock; then
printf "Failed to acquire lock.\n" >&2
exit 1
fi
trap 'rm -rf /tmp/abc.lock' EXIT # remove the lockdir on exit
# rest of script ...
See Bash FAQ 45 for other ways of locking.
Solution 3:
This is what I use:
#!/bin/bash
#check if abc is running
if pgrep abc >/dev/null 2>&1
then
# abc is running
else
# abc is not running
fi
In plain English: if 'pgrep' returns 0, the process is running, otherwise it is not.
Related reading:
Bash Scripting :: String Comparisons
Ubuntu Manuals pgrep