Skip to content

Instantly share code, notes, and snippets.

@benahm
Created June 4, 2014 13:58
Show Gist options
  • Save benahm/f7119f533cd1789fdc38 to your computer and use it in GitHub Desktop.
Save benahm/f7119f533cd1789fdc38 to your computer and use it in GitHub Desktop.
Locking a bash script against a parallel run
lockfile=/var/tmp/mylock
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; then
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
# do stuff here
# clean up after yourself, and release your trap
rm -f "$lockfile"
trap - INT TERM EXIT
else
echo "Lock Exists: $lockfile owned by $(cat $lockfile)"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment