Skip to content

Instantly share code, notes, and snippets.

@omnisis
Last active December 12, 2015 10:29
Show Gist options
  • Save omnisis/4759486 to your computer and use it in GitHub Desktop.
Save omnisis/4759486 to your computer and use it in GitHub Desktop.
Bash script for avoid parallel executions
#!/bin/bash
#####################################################################
# Script to ensure that a cmd does not have parallel executions.
#####################################################################
unset LOCKFILE
while getopts l: flag; do
case $flag in
l)
LOCKFILE=$OPTARG
shift; shift
;;
esac
done
if [ -z "$LOCKFILE" ]; then
echo "usage: solo -l lockfile cmdline"; echo
echo " lockfile The lockfile to use (e.g. /tmp/mylock)"; echo
echo " cmdline The cmdline to run solo"; echo
exit 1
fi
# Use BASH's builtin 'noclobber' trick to test the lockfile
if ( set -o noclobber; echo $$ > "$LOCKFILE") 2>/dev/null; then
# set trap to remove the lockfile on exit
trap 'rm -f "$LOCKFILE" >/dev/null 2>&1' 0
# handle non-std termination by returning status=2
trap 'exit 2' 1 2 3 15
# eval all arguments passed to us
eval "$*"
else
OTHERPID=$(cat $LOCKFILE 2>/dev/null)
if ps -A | cut -f1 -d' ' | grep $OTHERPID >/dev/null 2>&1; then
echo "Lockfile exists: $LOCKFILE owned by: $OTHERPID "
else
echo "Detected stale lockfile, removing for next run .."
rm -rf "$LOCKFILE" >/dev/null 2>&1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment