Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script: Ensure that script isn't executed if already running [duplicate]

Tags:

bash

shell

cron

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?

like image 372
Industrial Avatar asked Jan 22 '11 15:01

Industrial


People also ask

How would you write a script that will not run if it is already running?

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.

How do you check if a 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 I make sure only one instance of a bash script runs?

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.

What is $@ in shell script?

$@ 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.


2 Answers

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.

like image 164
Arnaud Le Blanc Avatar answered Oct 18 '22 18:10

Arnaud Le Blanc


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.

like image 41
paxdiablo Avatar answered Oct 18 '22 20:10

paxdiablo