Possible Duplicate:
Quick-and-dirty way to ensure only one instance of a shell script is running at a time
I've set up a cronjob to backup my folders properly which I am quite proud of. However I've found out, by looking at the results from the backups, that my backup script has been called more than once by Crontab, resulting in multiple backups running at the same time.
Is there any way I can ensure that a certain shell script to not run if the very same script already is executing?
We can use the parameter -n to use flock in a non-blocking way. This will make flock immediately exit with an error when there is another lock on the file. We should use -n if we don't want the script to run a second time in the event that it's 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.
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.
$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
A solution without race condition or early exit problems is to use a lock file. The flock
utility handles this very well and can be used like this:
flock -n /var/run/your.lockfile -c /your/script
It will return immediately with a non 0 status if the script is already running.
The usual and simple way to do this is to put something like:
if [[ -f /tmp/myscript.running ]] ; then
exit
fi
touch /tmp/myscript.running
at the top of you script and
rm -f /tmp/myscript.running
at the end, and in trap
functions in case it doesn't reach the end.
This still has a few potential problems (such as a race condition at the top) but will do for the vast majority of cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With