Skip to content

Instantly share code, notes, and snippets.

@stefanlasiewski
Last active September 18, 2015 18:32
Show Gist options
  • Save stefanlasiewski/79de6aa498f85baeed57 to your computer and use it in GitHub Desktop.
Save stefanlasiewski/79de6aa498f85baeed57 to your computer and use it in GitHub Desktop.
This example script will check to make sure that an earlier instance isn't already running before executing again. Useful for cronjobs that run every 5 minutes, and you don't want a backlog of processes piling up because of a slowness issue
#!/bin/sh
# This example script will check to make sure that an earlier instance isn't already running before executing again.
# Useful for cronjobs that run every 5 minutes, and you don't want a backlog of processes piling up because of a slowness issue
# Borrowed from http://stackoverflow.com/questions/1440967/how-do-i-make-sure-my-bash-script-isnt-already-running
# Modified to work on FreeBSD as well as Linux
# Example usage:
#$ ./checkIfRunning.sh
#Sleeping for 600 seconds.
#^Z
#[1]+ Stopped ./checkIfRunning.sh
#$ bg
#[1]+ ./checkIfRunning.sh &
#./checkIfRunning.sh
#[4214] NOTICE: Script is already running. Exiting.
#$ ./checkIfRunning.sh
#[4219] NOTICE: Script is already running. Exiting.
#$
ME=`basename $0`
PATH=$PATH:/usr/local/bin
checkIfRunning () {
# Check to see if we are already running:
# http://stackoverflow.com/questions/1440967/how-do-i-make-sure-my-bash-script-isnt-already-running
# Modified for FreeBSD
# Use a lockfile containing the pid of the running process
# If script crashes and leaves lockfile around, it will have a different pid so
# will not prevent script running again.
lockfile=/tmp/$ME.lockfile
# Create empty lock file if none exists
touch $lockfile
read lastPID < $lockfile
# If lastPID is not null and a process with that pid exists, then exit.
[ ! -z "$lastPID" -a `pgrep -F $lockfile 2> /dev/null` ] && { echo "[$$] NOTICE: Script is already running. Exiting." && exit 0 ; }
# save my pid in the lock file
echo $$ > $lockfile
}
# Wrap everything else into a {} block, for easier control and logging
doit () {
checkIfRunning
# Your code here
echo "Sleeping for 600 seconds."
sleep 600
echo "Hello world!"
}
# Do it!
doit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment