Skip to content

Instantly share code, notes, and snippets.

@elfsternberg
Forked from andremueller/bash_template.sh
Created April 6, 2022 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elfsternberg/4a9bfc80bef0960f32c12b6ae1dfe2a9 to your computer and use it in GitHub Desktop.
Save elfsternberg/4a9bfc80bef0960f32c12b6ae1dfe2a9 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