Skip to content

Instantly share code, notes, and snippets.

@andremueller
Created April 2, 2022 16:10
Show Gist options
  • Save andremueller/878a54dfb943575b299f22601d27f891 to your computer and use it in GitHub Desktop.
Save andremueller/878a54dfb943575b299f22601d27f891 to your computer and use it in GitHub Desktop.
A bash template with argument parsing and error handling
#!/bin/bash
# my bash template
set -o errexit
set -o nounset
shopt -s nullglob
SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
function die() {
echo "ERROR $? IN ${BASH_SOURCE[0]} AT LINE ${BASH_LINENO[0]}" 1>&2
exit 1
}
trap die ERR
function usage() {
cat <<EOF
Usage ${SCRIPT_PATH}/$0 OPTIONS
Options:
--version=N sets the version
-d start in daemon mode
--help, -h this help
EOF
}
# parse arguments
version=""
daemon=0
args=()
while [[ $# -gt 0 ]]; do
case "$1" in
-v=* | --version=*)
# set an option with argument
version="${1#*=}"
;;
-d | --daemon)
# set a binary option
daemon=1
;;
-h | --help)
usage
exit 0
;;
--)
# forward all arguments after `--` to the command
shift
args+=("${@}")
break
;;
*)
echo "ERROR: unknown option '$1'"
usage
exit 1
;;
esac
shift
done
# OK do here something with "${args[@]}"
echo "SCRIPT_PATH = ${SCRIPT_PATH}"
echo "args = ${args[*]:-}"
echo "version = $version"
echo "daemon = $daemon"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment