Sunday, October 9, 2022

[SOLVED] How to make sure only one instance of a Bash script is running at a time?

Issue

I want to make a sh script that will only run at most once at any point.

Say, if I exec the script then I go to exec the script again, how do I make it so that if the first exec of the script is still working the second one will fail with an error. I.e. I need to check if the script is running elsewhere before doing anything. How would I go about doing this??

The script I have runs a long running process (i.e. runs forever). I wanted to use something like cron to call the script every 15mins so in case the process fails, it will be restarted by the next cron run script.


Solution

You want a pid file, maybe something like this:

pidfile=/path/to/pidfile
if [ -f "$pidfile" ] && kill -0 `cat $pidfile` 2>/dev/null; then
    echo still running
    exit 1
fi  
echo $$ > $pidfile


Answered By - cxreg
Answer Checked By - Marie Seifert (WPSolving Admin)