Skip to content

Instantly share code, notes, and snippets.

@dsiebel
Created June 2, 2021 07:30
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 dsiebel/a04352dc6758d8b839603eb8d65a9003 to your computer and use it in GitHub Desktop.
Save dsiebel/a04352dc6758d8b839603eb8d65a9003 to your computer and use it in GitHub Desktop.
Minimal bash script template
#!/usr/bin/env bash
# Original version: https://betterdev.blog/minimal-safe-bash-script-template/
# Minor adjustments for positional arguments, debug output, remove colors and such.
set -Eeuo pipefail
trap cleanup SIGINT SIGTERM ERR EXIT
#script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd -P)
script_name=$(basename "${BASH_SOURCE[0]}")
usage() {
cat <<EOF
Usage: ${script_name} [-h] [-v] [-f] -p param_value arg1 [arg2...]
Script description here.
Available options:
-h, --help Print this help and exit
-v, --verbose Print script debug info
-f, --flag Some flag description
-p, --param Some param description
EOF
exit
}
cleanup() {
trap - SIGINT SIGTERM ERR EXIT
# script cleanup here
}
msg() {
echo >&2 -e "${1-}"
}
die() {
msg "$1"
exit "${2-1}"
}
parse_params() {
# default values of variables set from arguments and options
args=()
while (( $# > 0 )); do
case "${1-}" in
--help | -h) usage ;;
--verbose | -v)
VERBOSE=1
set -x
;;
-?*) die "Unknown option: $1" ;;
*)
args+=("${1-}")
;;
esac
shift
done
# check required options
# [[ -z "${param-}" ]] && die "Missing required parameter: param"
# check required arguments
# (( ${#args[@]} < 2 )) && die "${script_name} expects 2 arguments, got ${#args[@]}" 1
# restore arguments
set -- "${args[@]}"
return 0
}
parse_params "$@"
# script logic here
if [[ -v VERBOSE ]]; then
msg "- arguments: ${args[*]-}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment