-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
bash-simple-plus
executable file
·384 lines (349 loc) · 10.9 KB
/
bash-simple-plus
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#!/usr/bin/env bash
# _ _
# ___(_)_ __ ___ _ __ | | ___ _
# / __| | '_ ` _ \| '_ \| |/ _ \_| |_
# \__ \ | | | | | | |_) | | __/_ _|
# |___/_|_| |_| |_| .__/|_|\___| |_|
# |_|
#
# Boilerplate for creating a simple bash script with some basic strictness
# checks, help features, easy debug printing.
#
# Usage:
# bash-simple-plus <options>...
#
# Depends on:
# list
# of
# programs
# expected
# in
# environment
#
# Bash Boilerplate: https://github.com/xwmx/bash-boilerplate
#
# Copyright (c) 2015 William Melody • hi@williammelody.com
# Notes #######################################################################
# Extensive descriptions are included for easy reference.
#
# Explicitness and clarity are generally preferable, especially since bash can
# be difficult to read. This leads to noisier, longer code, but should be
# easier to maintain. As a result, some general design preferences:
#
# - Use leading underscores on internal variable and function names in order
# to avoid name collisions. For unintentionally global variables defined
# without `local`, such as those defined outside of a function or
# automatically through a `for` loop, prefix with double underscores.
# - Always use braces when referencing variables, preferring `${NAME}` instead
# of `$NAME`. Braces are only required for variable references in some cases,
# but the cognitive overhead involved in keeping track of which cases require
# braces can be reduced by simply always using them.
# - Prefer `printf` over `echo`. For more information, see:
# http://unix.stackexchange.com/a/65819
# - Prefer `$_explicit_variable_name` over names like `$var`.
# - Use the `#!/usr/bin/env bash` shebang in order to run the preferred
# Bash version rather than hard-coding a `bash` executable path.
# - Prefer splitting statements across multiple lines rather than writing
# one-liners.
# - Group related code into sections with large, easily scannable headers.
# - Describe behavior in comments as much as possible, assuming the reader is
# a programmer familiar with the shell, but not necessarily experienced
# writing shell scripts.
###############################################################################
# Strict Mode
###############################################################################
# Treat unset variables and parameters other than the special parameters ‘@’ or
# ‘*’ as an error when performing parameter expansion. An 'unbound variable'
# error message will be written to the standard error, and a non-interactive
# shell will exit.
#
# This requires using parameter expansion to test for unset variables.
#
# http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
#
# The two approaches that are probably the most appropriate are:
#
# ${parameter:-word}
# If parameter is unset or null, the expansion of word is substituted.
# Otherwise, the value of parameter is substituted. In other words, "word"
# acts as a default value when the value of "$parameter" is blank. If "word"
# is not present, then the default is blank (essentially an empty string).
#
# ${parameter:?word}
# If parameter is null or unset, the expansion of word (or a message to that
# effect if word is not present) is written to the standard error and the
# shell, if it is not interactive, exits. Otherwise, the value of parameter
# is substituted.
#
# Examples
# ========
#
# Arrays:
#
# ${some_array[@]:-} # blank default value
# ${some_array[*]:-} # blank default value
# ${some_array[0]:-} # blank default value
# ${some_array[0]:-default_value} # default value: the string 'default_value'
#
# Positional variables:
#
# ${1:-alternative} # default value: the string 'alternative'
# ${2:-} # blank default value
#
# With an error message:
#
# ${1:?'error message'} # exit with 'error message' if variable is unbound
#
# Short form: set -u
set -o nounset
# Exit immediately if a pipeline returns non-zero.
#
# NOTE: This can cause unexpected behavior. When using `read -rd ''` with a
# heredoc, the exit status is non-zero, even though there isn't an error, and
# this setting then causes the script to exit. `read -rd ''` is synonymous with
# `read -d $'\0'`, which means `read` until it finds a `NUL` byte, but it
# reaches the end of the heredoc without finding one and exits with status `1`.
#
# Two ways to `read` with heredocs and `set -e`:
#
# 1. set +e / set -e again:
#
# set +e
# read -rd '' variable <<HEREDOC
# HEREDOC
# set -e
#
# 2. Use `<<HEREDOC || true:`
#
# read -rd '' variable <<HEREDOC || true
# HEREDOC
#
# More information:
#
# https://www.mail-archive.com/bug-bash@gnu.org/msg12170.html
#
# Short form: set -e
set -o errexit
# Allow the above trap be inherited by all functions in the script.
#
# Short form: set -E
set -o errtrace
# Return value of a pipeline is the value of the last (rightmost) command to
# exit with a non-zero status, or zero if all commands in the pipeline exit
# successfully.
set -o pipefail
# Set $IFS to only newline and tab.
#
# http://www.dwheeler.com/essays/filenames-in-shell.html
IFS=$'\n\t'
###############################################################################
# Environment
###############################################################################
# $_ME
#
# This program's basename.
_ME="$(basename "${0}")"
###############################################################################
# Debug
###############################################################################
# _debug()
#
# Usage:
# _debug <command> <options>...
#
# Description:
# Execute a command and print to standard error. The command is expected to
# print a message and should typically be either `echo`, `printf`, or `cat`.
#
# Example:
# _debug printf "Debug info. Variable: %s\\n" "$0"
__DEBUG_COUNTER=0
_debug() {
if ((${_USE_DEBUG:-0}))
then
__DEBUG_COUNTER=$((__DEBUG_COUNTER+1))
{
# Prefix debug message with "bug (U+1F41B)"
printf "🐛 %s " "${__DEBUG_COUNTER}"
"${@}"
printf "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――\\n"
} 1>&2
fi
}
###############################################################################
# Error Messages
###############################################################################
# _exit_1()
#
# Usage:
# _exit_1 <command>
#
# Description:
# Exit with status 1 after executing the specified command with output
# redirected to standard error. The command is expected to print a message
# and should typically be either `echo`, `printf`, or `cat`.
_exit_1() {
{
printf "%s " "$(tput setaf 1)!$(tput sgr0)"
"${@}"
} 1>&2
exit 1
}
# _warn()
#
# Usage:
# _warn <command>
#
# Description:
# Print the specified command with output redirected to standard error.
# The command is expected to print a message and should typically be either
# `echo`, `printf`, or `cat`.
_warn() {
{
printf "%s " "$(tput setaf 1)!$(tput sgr0)"
"${@}"
} 1>&2
}
###############################################################################
# Help
###############################################################################
# _print_help()
#
# Usage:
# _print_help
#
# Description:
# Print the program help information.
_print_help() {
cat <<HEREDOC
_ _
___(_)_ __ ___ _ __ | | ___ _
/ __| | '_ \` _ \\| '_ \\| |/ _ \\_| |_
\\__ \\ | | | | | | |_) | | __/_ _|
|___/_|_| |_| |_| .__/|_|\\___| |_|
|_|
Boilerplate for creating a simple bash script with some basic strictness
checks and help features, and easy debug printing, and basic option handling.
Usage:
${_ME} [--options] [<arguments>]
${_ME} -h | --help
Options:
-h --help Display this help information.
HEREDOC
}
###############################################################################
# Options
#
# NOTE: The `getops` builtin command only parses short options and BSD `getopt`
# does not support long arguments (GNU `getopt` does), so the most portable
# and clear way to parse options is often to just use a `while` loop.
#
# For a pure bash `getopt` function, try pure-getopt:
# https://github.com/agriffis/pure-getopt
#
# More info:
# http://wiki.bash-hackers.org/scripting/posparams
# http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
# http://stackoverflow.com/a/14203146
# http://stackoverflow.com/a/7948533
# https://stackoverflow.com/a/12026302
# https://stackoverflow.com/a/402410
###############################################################################
# Parse Options ###############################################################
# Initialize program option variables.
_PRINT_HELP=0
_USE_DEBUG=0
# Initialize additional expected option variables.
_OPTION_X=0
_SHORT_OPTION=
_LONG_OPTION=
# __get_option_value()
#
# Usage:
# __get_option_value <option> <value>
#
# Description:
# Given a flag (e.g., -e | --example) return the value or exit 1 if value
# is blank or appears to be another option.
__get_option_value() {
local __arg="${1:-}"
local __val="${2:-}"
if [[ -n "${__val:-}" ]] && [[ ! "${__val:-}" =~ ^- ]]
then
printf "%s\\n" "${__val}"
else
_exit_1 printf "%s requires a valid argument.\\n" "${__arg}"
fi
}
while ((${#}))
do
__arg="${1:-}"
__val="${2:-}"
case "${__arg}" in
-h|--help)
_PRINT_HELP=1
;;
--debug)
_USE_DEBUG=1
;;
-x|--option-x)
_OPTION_X=1
;;
-o)
_SHORT_OPTION="$(__get_option_value "${__arg}" "${__val:-}")"
shift
;;
--long-option)
_LONG_OPTION="$(__get_option_value "${__arg}" "${__val:-}")"
shift
;;
--endopts)
# Terminate option parsing.
break
;;
-*)
_exit_1 printf "Unexpected option: %s\\n" "${__arg}"
;;
esac
shift
done
###############################################################################
# Program Functions
###############################################################################
_simple() {
_debug printf ">> Performing operation...\\n"
if ((_OPTION_X))
then
printf "Perform a simple operation with --option-x.\\n"
else
printf "Perform a simple operation.\\n"
fi
if [[ -n "${_SHORT_OPTION}" ]]
then
printf "Short option value: %s\\n" "${_SHORT_OPTION}"
fi
if [[ -n "${_LONG_OPTION}" ]]
then
printf "Long option value: %s\\n" "${_LONG_OPTION}"
fi
}
###############################################################################
# Main
###############################################################################
# _main()
#
# Usage:
# _main [<options>] [<arguments>]
#
# Description:
# Entry point for the program, handling basic option parsing and dispatching.
_main() {
if ((_PRINT_HELP))
then
_print_help
else
_simple "$@"
fi
}
# Call `_main` after everything has been defined.
_main "$@"