Skip to content

Instantly share code, notes, and snippets.

@jiahaog
Last active March 10, 2016 15:42
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 jiahaog/cf38c96dd0a1888a0bf5 to your computer and use it in GitHub Desktop.
Save jiahaog/cf38c96dd0a1888a0bf5 to your computer and use it in GitHub Desktop.
Template for shell scripts with proper error catching
#!/bin/sh
# Template for shell scripts with proper error catching
# Modified from http://www.alittlemadness.com/2012/06/25/bash-tip-reliable-clean-up-with-trap/
# immediately fail on error anywhere
set -e
# Defines a working area on the file system.
TEMP_DIR=/tmp/$$.scratch
function cleanUp() {
if [[ -d "${TEMP_DIR}" ]]
then
rm -r "${TEMP_DIR}"
fi
}
trap cleanUp EXIT
mkdir "${TEMP_DIR}"
# Do things below, placing temp files in $TEMP_DIR
# We succeeded, reset trap and clean up normally.
trap - EXIT
cleanUp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment