-
-
Save elfsternberg/4a9bfc80bef0960f32c12b6ae1dfe2a9 to your computer and use it in GitHub Desktop.
A bash template with argument parsing and error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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