Skip to content

Instantly share code, notes, and snippets.

@beugley
Created November 23, 2016 14:54
Show Gist options
  • Save beugley/43f3feb8c532f7cc07cbcb3ea3ccd203 to your computer and use it in GitHub Desktop.
Save beugley/43f3feb8c532f7cc07cbcb3ea3ccd203 to your computer and use it in GitHub Desktop.
function to prevent multiple instances of a script from running (works for bash or ksh)
#!/bin/sh
#
# To prevent multiple instances of a script from executing concurrently,
# include this function, and a statement to invoke it, at the top of any
# ksh/bash script. This function will check for other instances of the
# same script that are executing by the same user. If any are found, then
# this instance terminates immediately.
#
# When scripts are invoked in a repetitive manner (cron or other scheduler),
# it's possible that an instance can still be running when the time arrives
# to start a new instance. For example, suppose that you schedule a script
# to run every 15 minutes, but one run takes 20 minutes? You may not want
# 2 (or more) concurrent instances of the script to run.
#
function TerminateIfAlreadyRunning
{
##
## Terminate if another instance of this script is already running.
##
SCRIPT_NAME=`/bin/basename $1`
echo "`/bin/date +%Y%m%d.%H%M%S:` This instance of $SCRIPT_NAME is PID $$"
for PID in `/bin/ps -fC $SCRIPT_NAME | /bin/grep "^$USER" | /usr/bin/awk '{print $2}'`
do
ALIVE=`/bin/ps -p $PID -o pid=`
if [[ "$PID" != "$$" && "$ALIVE" != "" ]]
then
echo "WARNING: $SCRIPT_NAME is already running as process $PID!"
echo "Terminating..."
exit 0
fi
done
}
TerminateIfAlreadyRunning $0
# Insert your script logic here...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment