Skip to content

Instantly share code, notes, and snippets.

@powersj
Created September 6, 2017 20:47
Show Gist options
  • Save powersj/b8f11b824e0827aead3ab47d63cb5d72 to your computer and use it in GitHub Desktop.
Save powersj/b8f11b824e0827aead3ab47d63cb5d72 to your computer and use it in GitHub Desktop.
Bash Shell Script Template
#!/bin/bash
# Bash script template
#
# Copyright 2017 Canonical Ltd.
# Joshua Powers <[email protected]>
VERBOSITY=0
TEMP_D=""
error() { echo "$@" 1>&2; }
fail() { [ $# -eq 0 ] || error "$@"; exit 1; }
bad_usage() { usage 1>&2; [ $# -eq 0 ] || error "$@"; return 1; }
cleanup() {
[ -z "${TEMP_D}" ] || [ ! -d "${TEMP_D}" ] || rm -Rf "${TEMP_D}"
}
debug() {
local level=${1}; shift;
[ "${level}" -gt "${VERBOSITY}" ] && return
error "${@}"
}
usage() {
cat <<EOF
Usage: ${0##*/} [ options ] <<ARGUMENTS>>
<<SUMMARY HERE>>
options:
<<OPTIONS HERE>>
EOF
}
main() {
local short_opts="ho:v"
local long_opts="help,output:,verbose"
local getopt_out=""
getopt_out=$(getopt --name "${0##*/}" \
--options "${short_opts}" --long "${long_opts}" -- "$@") ||
{ bad_usage; return; }
eval set -- "${getopt_out}" ||
{ bad_usage; return; }
## <<insert default variables here>>
local output=""
local cur="" next=""
while [ $# -ne 0 ]; do
cur="$1"; next="$2";
case "$cur" in
-h|--help) usage ; exit 0;;
-o|--output) output=$next; shift;;
-v|--verbose) VERBOSITY=$((VERBOSITY+1));;
--) shift; break;;
esac
shift;
done
## check arguments here - how many args do you expect?
#[ $# -lt 3 ] && { bad_usage "must provide 3 args"; return; }
[ $# -ne 1 ] || { bad_usage "must provide arguments"; return; }
TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${0##*/}.XXXXXX") ||
fail "failed to make tempdir"
trap cleanup EXIT
# program starts here
echo "Hello World."
echo "$output"
i=0; for x in "$@"; do i=$((i+1)); echo "arg[$i]:$x"; done
return 0
}
main "$@"
# vi: ts=4 noexpandtab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment