Created
August 21, 2012 15:04
-
-
Save gtenagli/3416297 to your computer and use it in GitHub Desktop.
Bash script must-haves
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Taken from http://www.davidpashley.com/articles/writing-robust-shell-scripts.html | |
# abort when trying to use an unset variable | |
set -u # or set -o nounset | |
# exit on non-zero return codes from statements | |
# note: checking $? won't work any more, should use: | |
# command || { echo "command failed"; exit 1; } | |
set -e # or set -o errexit | |
# avoid race conditions | |
if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; | |
then | |
trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT | |
# critical-section | |
rm -f "$lockfile" | |
trap - INT TERM EXIT # reset to the previous handler | |
else | |
echo "Failed to acquire lockfile: $lockfile." | |
echo "Held by $(cat $lockfile)" | |
fi | |
# rollback handler in case of premature exits | |
rollback() { | |
# do clean up | |
} | |
trap rollback INT TERM EXIT | |
# do something | |
trap - INT TERM EXIT | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment