Skip to content

Instantly share code, notes, and snippets.

@rsperl
Last active July 25, 2022 15:27
Show Gist options
  • Save rsperl/6c570189a308ee60fc575e0378d89086 to your computer and use it in GitHub Desktop.
Save rsperl/6c570189a308ee60fc575e0378d89086 to your computer and use it in GitHub Desktop.
using lockfiles in bash #snippet
# src: http://www.davidpashley.com/articles/writing-robust-shell-scripts/
# noclobber will not redirect to an existing file
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
then
# we have the lockfile, so be sure to remove it if the script exits early
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
# do our critical stuff
# remote the lockfile
rm -f "$lockfile"
# remove our trap
trap - INT TERM EXIT
else
echo "Failed to acquire lockfile: $lockfile."
echo "Held by $(cat $lockfile)"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment