-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptions.sh
52 lines (51 loc) · 1.3 KB
/
options.sh
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
#!/usr/bin/env bash
# shellcheck disable=all
#
# Options and flags
#
# Sources:
#
# https://linuxcommand.org/lc3_adv_standards.php
# https://stackoverflow.com/a/28466267/519360
# Options and flags from command line
needs_arg() {
if [[ -z "$OPTARG" ]]; then
error_exit "Error: Argument required for option '$OPT' but none provided."
fi
}
# Set flag-created variables to false by default
quiet_mode=false
# Run the comparison (be sure to change the "getopts" below!)
while getopts :dt-:qh OPT; do
# Using help flag only? The above should be:
# while getopts :-:h OPT; do
if [[ "$OPT" = "-" ]]; then # long option: reformulate OPT and OPTARG
OPT="${OPTARG%%=*}" # extract long option name
OPTARG="${OPTARG#$OPT}" # extract long option argument (may be empty)
OPTARG="${OPTARG#=}" # remove assigning `=`
else
OPTARG="${OPTARG:-}"
fi
case "$OPT" in
h | help)
help_message
graceful_exit
;;
q | quiet)
quiet_mode=true
;;
d | date)
needs_arg
date="$OPTARG"
;;
??*) # bad long option
usage >&2
error_exit "Unknown option --$OPT"
;;
?) # bad short option
usage >&2
error_exit "Unknown option -$OPTARG"
;;
esac
done
shift $((OPTIND - 1)) # remove parsed options and args from $@ list