Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make sure my bash script isn't already running?

Tags:

bash

I have a bash script I want to run every 5 minutes from cron... but there's a chance the previous run of the script isn't done yet... in this case, i want the new run to just exit. I don't want to rely on just a lock file in /tmp.. I want to make sure sure the process is actually running before i honor the lock file (or whatever)...

Here is what I have stolen from the internet so far... how do i smarten it up a bit? or is there a completely different way that's better?

if [ -f /tmp/mylockFile ] ; then
  echo 'Script is still running'
else
  echo 1 > /tmp/mylockFile
  /* Do some stuff */
  rm -f /tmp/mylockFile
fi
like image 570
danb Avatar asked Sep 17 '09 19:09

danb


People also ask

How do you check if a Bash script is already running?

An easier way to check for a process already executing is the pidof command. Alternatively, have your script create a PID file when it executes. It's then a simple exercise of checking for the presence of the PID file to determine if the process is already running. #!/bin/bash # abc.sh mypidfile=/var/run/abc.

How do you check if a script is already running?

Every running process has a PID. We use pidof command to determine the PID of our shell script. If the PID exists, it means the shell script is already running. In such cases, the above script will display a message saying that the process is already running.

How do I stop a Bash script from running?

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.

How do I make sure only one instance of a Bash script runs?

How to Ensure Only One Instance of a Bash Script Is Running 🏃 Just add the pidof line at the top of your Bash script, and you'll be sure that only one instance of your script can be running at a time.


1 Answers

# Use a lockfile containing the pid of the running process
# If script crashes and leaves lockfile around, it will have a different pid so
# will not prevent script running again.
# 
lf=/tmp/pidLockFile
# create empty lock file if none exists
cat /dev/null >> $lf
read lastPID < $lf
# if lastPID is not null and a process with that pid exists , exit
[ ! -z "$lastPID" -a -d /proc/$lastPID ] && exit
echo not running
# save my pid in the lock file
echo $$ > $lf
# sleep just to make testing easier
sleep 5

There is at least one race condition in this script. Don't use it for a life support system, lol. But it should work fine for your example, because your environment doesn't start two scripts simultaneously. There are lots of ways to use more atomic locks, but they generally depend on having a particular thing optionally installed, or work differently on NFS, etc...

like image 182
DigitalRoss Avatar answered Nov 15 '22 18:11

DigitalRoss