Tuesday, August 5, 2014

Prevent bash script from executing when same script is already running

I needed to prevent my bash script from executing (duplicating) and did not want to go searching our code base...
so I searched google instead :)


pidof -x option allows for searching for scripts being executed without specifying more than the script name.

$$ is the PID for the current process.

pidof will return an array of pids. Just check if any of the PIDs are not equivalent to this one.


# exit if I am already running
for pid in $(pidof -x rsync.sh); do
    if [ $pid != $$ ]; then
        echo "[$(date)] : abc.sh : Process is already running with PID $pid"
        exit 1

# .....