Created
March 22, 2024 01:09
-
-
Save kawata-atsushi/e49ff8d10f7810c099a04af4cb3128ba to your computer and use it in GitHub Desktop.
sample bash script. (Minimal safe Bash script template)
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
#!/usr/bin/env bash | |
set -Eeuo pipefail | |
function usage() { | |
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 | |
} | |
function msg() { | |
echo >&2 -e "${1:-}" | |
} | |
function die() { | |
local msg=$1 | |
local code=${2:-1} # default exit status 1 | |
msg "$msg" | |
exit "$code" | |
} | |
function 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 | |
;; | |
-?*) die "Unknown option: $1" ;; # die is the original function | |
*) break ;; | |
esac | |
shift | |
done | |
args=("$@") | |
# check required params and arguments | |
[[ -z "${param:-}" ]] && die "Missing required parameter: param" | |
[[ ${#args[@]} -eq 0 ]] && die "Missing script arguments" | |
return 0 | |
} | |
parse_params "$@" | |
# script logic here | |
echo "- flag: ${flag}" | |
echo "- param: ${param}" | |
echo "- arguments: ${args[*]:-}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment