-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbash_script.sh.template
112 lines (97 loc) · 2.53 KB
/
bash_script.sh.template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env bash
###################################################################
# Script Name : bash_script.sh.template
# Description : Template for a bash script with options.
# Args : None
# Author : Doug Emery
# Email : hummus.augment_0r@icloud.com
#
# Adapted from a gist by Ariel Balter, https://github.com/abalter:
#
# https://gist.github.com/abalter/4f1375985b99b84e62fcc0d63ef83174u
#
###################################################################
### utility variables
CMD=$(basename $0)
THIS_DIR="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
TIMESTAMP=$(date +"%Y-%m-%d")
### preallocate variables
required=
optional_hasarg=
got_opt_arg=false
optional_noarg=false
has_default="DEFAULT"
### initialize (clear) opt parsing variables
OPTIND=
OPTARG=
opt=
function usage {
echo "Usage: ${CMD} [-h] -a REQ [-b OPTHAS] [-c] [-d OPTDEF]"
}
function description {
cat <<EOF
Description:
------------
This demonstrates parsing arguments with getopts
Options:
-------------------
-h Print this help message and exit.
-a REQ Required opt that takes an argument.
-b OPTHAS Optional opt that takes an argument.
-c Optional opt that does not take an argument.
-d OPTDEF If given, sets value of has_default to OPTDEF.
Otherwise, the value of has_default defaults to
DEFAULT.
EOF
}
while getopts "ha:b:cd:" opt; do
case "$opt" in
h)
usage
description
exit 0
;;
a)
required=${OPTARG}
;;
b)
optional_hasarg=${OPTARG}
got_opt_arg=true
;;
c)
optional_noarg=true
;;
d)
has_default=${OPTARG}
;;
?)
usage
echo "Error: did not recognize option, ${OPTARG}."
echo "Please try -h for help."
exit 1
;;
esac
done
if [[ "$required" == "" ]]; then
echo "ERROR: Required option -a not set."
echo "Please try -h for help."
exit 1
fi
echo "required: $required"
if [[ "$got_opt_arg" == true ]]; then
if [[ "$optional_hasarg" == "" ]]; then
echo "-b option set but no argument given"
echo "Please try -h for help."
exit 1
else
echo "optional_hasarg: $optional_hasarg"
fi
else
echo "optional_hasarg not set"
fi
if [[ "$optional_noarg" == true ]]; then
echo "optional_noarg set"
else
echo "optional_noarg not set"
fi
echo "has_default: $has_default"