I'm currently creating a lock folder which is created when my script runs, I also move files into sub folders here for processing. When the script ends a TRAP is called which removes the lock folder and contents, all of which is working fine. We had an issue the other day when someone pulled the power from one of the servers so my TRAP was never called so when re-booted the lock folder was still there which meant my scripts couldn't re-start until they were manually removed. What's the best way of checking if the script is already running ? I currently have this approach using process id's:
if ! mkdir $LOCK_DIR 2>/dev/null; then # Try to create the lock dir. This should pass successfully first run. # If the lock dir exists pid=$(cat $LOCK_DIR/pid.txt) if [[ $(ps -ef | awk '{print $2}' | grep $pid | grep -v grep | wc -l) == 1 ]]; then echo "Script is already running" exit 1 else echo "It looks like the previous script was killed. Restarting process." # Do some cleanup here before removing dir and re-starting process. fi fi # Create a file in the lock dir containing the pid. Echo the current process id into the file. touch $LOCK_DIR/pid.txt echo $$ > $LOCK_DIR/pid.txt # Rest of script below
man 1 lockfile lockfile-check lockfile-create lockfile-remove lockfile-touchflockcommand.man flockcontains examplesflockYou can determine if there is a currently running version of your script, assuming it is the only one locking the file.flocklocks also automagically go away when your code closes the lockfile, so no extra cleanup is needed.