Check the closure of an application in the shell script [duplicate]
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.