bashshellprocesslockfile

Quick-and-dirty way to ensure only one instance of a shell script is running at a time


What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?


Solution

  • Here's an implementation that uses a lockfile and echoes a PID into it. This serves as a protection if the process is killed before removing the pidfile:

    LOCKFILE=/tmp/lock.txt
    if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
        echo "already running"
        exit
    fi
    
    # make sure the lockfile is removed when we exit and then claim it
    trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
    echo $$ > ${LOCKFILE}
    
    # do stuff
    sleep 1000
    
    rm -f ${LOCKFILE}
    

    The trick here is the kill -0 which doesn't deliver any signal but just checks if a process with the given PID exists. Also the call to trap will ensure that the lockfile is removed even when your process is killed (except kill -9).