User Tools

Site Tools


linux:bash_run_single_instance_script

Howto run a single instance for a bash script

21.08.2012

Let's assume that we have a script written in bash, and we want it to force a single run for it, at any given time.

For this, we'll be using a 'file lock' to check its existence in successive runs:

FILE_LOCK=/tmp/crontest.lock
 
function check_if_script_is_running {
    if [ -e  $FILE_LOCK ]; then
        echo "An already instance of this script is running " `cat $FILE_LOCK`
        exit 1
    fi
}
 
function create_lock {
    check_if_script_is_running
 
    pid=$$
    echo $pid > $FILE_LOCK
}
 
function remove_lock {
    rm $FILE_LOCK
}

And the usage for your script will be:

create_lock
...
remove_lock

Just keep in mind, if your script is killed by some external action, the remove_lock function will never be executed and therefore, you'll end up with a wrong file lock. The solution for this is to manually remove the file lock, so a proper message can be inserted in the check_if_script_is_running function.

linux/bash_run_single_instance_script.txt · Last modified: 2013/03/16 17:40 (external edit)