summaryrefslogtreecommitdiffstats
path: root/.local/bin/template.sh
diff options
context:
space:
mode:
Diffstat (limited to '.local/bin/template.sh')
-rw-r--r--.local/bin/template.sh100
1 files changed, 100 insertions, 0 deletions
diff --git a/.local/bin/template.sh b/.local/bin/template.sh
new file mode 100644
index 0000000..4afcb5f
--- /dev/null
+++ b/.local/bin/template.sh
@@ -0,0 +1,100 @@
1#!/usr/bin/env bash
2# https://betterdev.blog/minimal-safe-bash-script-template/
3
4set -Eeuo pipefail
5
6cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1
7
8trap cleanup SIGINT SIGTERM ERR EXIT
9
10usage() {
11 cat <<EOF
12Usage: $(basename "$0") [-h] [-v] [-f] -p param_value arg1 [arg2...]
13
14Script description here.
15
16Available options:
17
18-h, --help Print this help and exit
19-v, --verbose Print script debug info
20-f, --flag Some flag description
21-p, --param Some param description
22EOF
23 exit
24}
25
26cleanup() {
27 trap - SIGINT SIGTERM ERR EXIT
28 # script cleanup here
29}
30
31setup_colors() {
32 if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
33 NOCOLOR='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' BLUE='\033[0;34m' PURPLE='\033[0;35m' CYAN='\033[0;36m' YELLOW='\033[1;33m'
34 else
35 NOCOLOR='' RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW=''
36 fi
37}
38
39msg() {
40 echo >&2 -e "${1-}"
41}
42
43die() {
44 local msg=$1
45 local code=${2-1} # default exit status 1
46 msg "$msg"
47 exit "$code"
48}
49
50parse_params() {
51 # default values of variables set from params
52 flag=0
53 param=''
54
55 while :; do
56 case "${1-}" in
57 -h | --help)
58 usage
59 ;;
60 -v | --verbose)
61 set -x
62 ;;
63 --no-color)
64 NO_COLOR=1
65 ;;
66 -f | --flag) # example flag
67 flag=1
68 ;;
69 -p | --param) # example named parameter
70 param="${2-}"
71 shift
72 ;;
73 -?*)
74 die "Unknown option: $1"
75 ;;
76 *)
77 break
78 ;;
79 esac
80 shift
81 done
82
83 args=("$@")
84
85 # check required params and arguments
86 [[ -z "${param-}" ]] && die "Missing required parameter: param"
87 [[ ${#args[@]} -eq 0 ]] && die "Missing script arguments"
88
89 return 0
90}
91
92parse_params "$@"
93setup_colors
94
95# script logic here
96
97msg "${RED}Read parameters:${NOCOLOR}"
98msg "- flag: ${flag}"
99msg "- param: ${param}"
100msg "- arguments: ${args[*]-}"