Skip to content

Instantly share code, notes, and snippets.

@Ithanil
Forked from m-radzikowski/script-template.sh
Last active July 11, 2024 08:43
Show Gist options
  • Save Ithanil/b72d61091b73cd8cb0c33de3de593834 to your computer and use it in GitHub Desktop.
Save Ithanil/b72d61091b73cd8cb0c33de3de593834 to your computer and use it in GitHub Desktop.
Minimal safe Bash script template - see the article with full description: https://betterdev.blog/minimal-safe-bash-script-template/
#!/bin/bash
set -Eeuo pipefail
trap cleanup SIGINT SIGTERM ERR EXIT
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd -P)
usage() {
local code=${1-0} # specify exit code when used as alternative to die()
cat <<EOF
Usage: $(basename "${BASH_SOURCE[0]}") [-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 "$code"
}
cleanup() {
trap - SIGINT SIGTERM ERR EXIT
# script cleanup here
}
msg() {
echo >&2 -e "${1-}"
}
die() {
local msg=$1
local code=${2-1} # default exit status 1
msg "$msg"
exit "$code"
}
parse_params() {
# default values of variables set from params
FLAG=0
PARAM=''
while :; do
case "${1-}" in
-h | --help) usage ;;
-v | --verbose) set -x ;;
-f | --flag) FLAG=1 ;; # example flag
-p | --param) # example named parameter
PARAM="${2-}"
shift
;;
-?*) msg "Unknown option: $1" && usage 1;;
*) break ;;
esac
shift
done
ARGS=("$@")
# check required params and arguments
[[ -z "${PARAM-}" ]] && msg "Missing required parameter: param" && usage 1
[[ ${#ARGS[@]} -eq 0 ]] && msg "Missing script arguments" && usage 1
return 0
}
parse_params "$@"
# script logic here
msg "Read parameters:"
msg "- flag: ${FLAG}"
msg "- param: ${PARAM}"
msg "- arguments: ${ARGS[*]-}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment