Skip to content

Instantly share code, notes, and snippets.

@sirosen
Created May 10, 2017 16:31
Show Gist options
  • Save sirosen/c881c07bcf4f6141b2db78627161ef2e to your computer and use it in GitHub Desktop.
Save sirosen/c881c07bcf4f6141b2db78627161ef2e to your computer and use it in GitHub Desktop.
Useful bash funcs
# Shell Scripting Functions so that scripting is less sad
# not an executable script -- source me in other scripts!
# always start unset
unset abort_message
# start with default of 0
rc=0
# Abort with message
function abort () {
echo "$abort_message" >&2
exit $rc
}
# Check if abort is necessary, and if so do it
function check_rc () {
if [ $# -gt 0 ];
then
abort_message="$1"
fi
if [ $rc -ne 0 ];
then
abort
fi
}
# Check if abort is necessary, fetching rc first
function check_last_rc () {
# must be the first command of the function
rc=$?
check_rc "$@"
}
# always start unset
unset usage_message
# Send usage output, but don't necessarily exit
function usage () {
echo "USAGE: $usage_message" >&2
}
# Send usage error message and exit
function usage_error () {
abort_message="USAGE ERROR: $usage_message"
rc=2
abort
}
# checks for the '-h' option when no other options are allowed
# requires arguments of the form "<USAGE> $@"
function check_help_opt () {
usage_message="$1"
local OPTIND
shift 1
while getopts "h" option;
do
case "$option" in
h)
usage
exit 0
;;
esac
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment