You have various ways of checking if a program is running.
Checking for a running program with the same name
pidof xyz
This will print the pids of every program named "xyz
", and return with exit code 0
if a pid was found and 1
if not (so if you just want to know if the program is running, you just have to check the exit code of that command).
If you don't have pidof
:
ps aux | grep xyz.sh | grep -v grep
And check if the output is empty or not.
A more reliable solution
If you want something a bit more sophisticated (that will check if this script is running, and not just something with the same name), the solution is usually to create a pid file:
At the beginning of the script, check if the file /var/run/xyz.pid
exists. If it exists, then the program is already running. If not, then create it and continue your normal execution. At the end of the normal execution of the script, remove the file.
You may write the pid of the script as you create the xyz.pid
file. That way, if the user wants to stop the running script without killing it themselves, they can call the script again with an option like, for example, --stop
. Then your script can read the .pid
file and kill it properly (by sending a signal asking it to shut down gracefully for example).
This is the way a lot of services (some http servers for example) work.