Skip to content

Instantly share code, notes, and snippets.

@tsaavik
Created April 3, 2017 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsaavik/11499b9ec281f03c6a3683d526f4fc14 to your computer and use it in GitHub Desktop.
Save tsaavik/11499b9ec281f03c6a3683d526f4fc14 to your computer and use it in GitHub Desktop.
Atomic locking for bash scripts
#!/bin/bash
lockfile=/var/lock/$(basename $0)
#Redirects output of file descriptor 5 to lockfile while this script runs
exec 5>"${lockfile}"
# flock file descriptor 5, otherwise fail
if ! flock -n 5 ; then
echo "Exiting: Another instance of $0 is already running";
exit 1
fi
# We now have the lockfile until this script exits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment