Skip to content

Instantly share code, notes, and snippets.

@solidsnack
Created June 28, 2017 03:43
Show Gist options
  • Save solidsnack/89a0891ce54573aa73b15a8c23c84b8c to your computer and use it in GitHub Desktop.
Save solidsnack/89a0891ce54573aa73b15a8c23c84b8c to your computer and use it in GitHub Desktop.
Template script with basic help, error handling and utilities
#!/bin/bash
set -o errexit -o nounset -o pipefail
function -h {
cat <<USAGE
USAGE: template.bash
Implement your script with this template.
USAGE
}; function --help { -h ;} # A nice way to handle -h and --help
export LC_ALL=en_US.UTF-8 # A locale that works consistently
function main {
: Write functions for each script task. Change `main` to call one of them.
}
##################################################################### Utilities
function msg { out "$*" >&2 ;}
function err { local x=$? ; msg "$*" ; return $(( $x == 0 ? 1 : $x )) ;}
function out { printf '%s\n' "$*" ;}
# Handles "no-match" exit code specified by POSIX for filtering tools.
function maybe { "$@" || return $(( $? == 1 ? 0 : $? )) ;}
######################### Delegates to subcommands or runs main, as appropriate
if declare -f -- "${1:-}" >/dev/null
then "$@"
else main "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment