3 # Author: Steven Baltakatei Sandoval
4 # Description: Template for bash scripts.
5 # Note: Use hide-show-block function to aid readability. (ex: https://www.emacswiki.org/emacs/HideShow ).
7 #== Variable Initialization ==
9 #== Global constants ==
10 SCRIPT_TTL
=10 # Limit script life to this in seconds.
11 PATH
="/usr/local/bin/:$PATH" # Add user binary executable directory to PATH.
12 PATH
="/opt/bktei:$PATH" # Add 'optional' executable directory to PATH.
13 SCRIPT_HOSTNAME
=$
(hostname
) # Save hostname of system running this script.
14 SCRIPT_VERSION
="bktemplate.sh 0.0.0" # Define version of script. Used by function 'showVersion'.
15 SCRIPT_TIME_SHORT
="$(date +%Y%m%dT%H%M%S%z)" # Save current date & time in ISO-8601 format (YYYYmmddTHHMMSS+zzzz).
16 SCRIPT_DATE_SHORT
="$(date +%Y%m%d)" # Save current date in ISO-8601 format.
18 #== Function Definitions ==
20 # Yell, Die, Try Three-Fingered Claw technique
21 # Ref/Attrib: https://stackoverflow.com/a/25515370
22 yell
() { echo "$0: $*" >&2; }
23 die
() { yell
"$*"; exit 111; }
24 try
() { "$@" || die
"cannot $*"; }
28 # Usage: echo [ arguments ]
29 # Description: Prints provided arguments to stderr.
32 # Script function dependencies: none
33 # External function dependencies: echo
34 # Last modified: 2020-04-11T21:16Z
35 # Last modified by: Steven Baltakatei Sandoval
38 # [1]: # Roth, James (2010-06-07). ["How to print text to stderr instead of stdout"](https://stackoverflow.com/a/2990533). Licensed CC BY-SA 4.0.
40 echo "$@" 1>&2; # Define stderr echo function. See [1].
41 return 0; # Function finished.
42 } # Define stderr message function.
44 # Usage: vbm "DEBUG:verbose message here"
45 # Description: Prints verbose message ("vbm") to stderr if OPTION_VERBOSE is set to "true".
47 # - OPTION_VERBOSE variable set by processArguments function. (ex: "true", "false")
48 # - "$@" positional arguments fed to this function.
50 # Script function dependencies: echoerr
51 # External function dependencies: echo
52 # Last modified: 2020-04-11T23:57Z
53 # Last modified by: Steven Baltakatei Sandoval
57 if [ "$OPTION_VERBOSE" == "true" ]; then
58 FUNCTION_TIME
=$
(date --iso-8601=ns
); # Save current time in nano seconds.
59 echoerr
"[$FUNCTION_TIME] ""$@"; # Display argument text.
63 return 0; # Function finished.
64 } # Verbose message display function.
67 # Description: Runs command; reports success if command exit code 0; exits otherwise.
70 # Script function dependencies: none
71 # Last modified: 2020-06-19T22:09Z
72 # Last modified by: Steven Baltakatei Sandoval
74 # Ref.Attrib: https://stackoverflow.com/a/18880585
77 if [ $return_value != 0 ]; then
78 echo "Command $1 failed";
81 echo "output: $cmd_output";
82 echo "Command succeeded.";
88 # Description: Displays script usage information.
91 # Script function dependencies: echoerr
92 # External dependencies: bash (5.0.3), echo
93 # Last modified: 2020-05-04T16:11Z
94 # Last modified by: Steven Baltakatei Sandoval
99 echoerr
" bktemplate.sh [ options ]"
102 echoerr
" -h, --help"
103 echoerr
" Display help information."
106 echoerr
" Display script version."
108 echoerr
" -v, --verbose"
109 echoerr
" Display debugging info."
111 echoerr
" -o, --output-file [ file ]"
112 echoerr
" Specify output file."
114 echoerr
" -i, --input-file [ file ]"
115 echoerr
" Specify input file."
117 echoerr
" -o, --output-dir [ directory ]"
118 echoerr
" Specify output directory."
120 echoerr
" -i, --input-dir [ directory ]"
121 echoerr
" Specify input directory."
125 return 0; # Function finished.
126 } # Display information on how to use this script.
129 # Descriptoin: Displays script version and license information.
132 # Script function dependencies: echoerr
133 # External function dependencies: echo
134 # Last modified: 2020-04-11T23:57Z
135 # Last modified by: Steven Baltakatei Sandoval
139 # Initialize function
140 vbm
"DEBUG:showVersion function called."
143 OUTPUT
="$SCRIPT_VERSION"
149 vbm
"DEBUG:showVersion function ended."
150 return 0; # Function finished.
151 } # Display script version.
153 # Usage: processArguments "$@"
154 # Description: Processes provided arguments in order to set script option variables useful for
155 # changing how other functions behave. For example, it may:
156 # 1. Activate verbose mode
157 # Input: "$@" (list of arguments provided to the function)
158 # Output: Sets following variables used by other functions:
159 # OPTION_VERBOSE Indicates verbose mode enable status. (ex: "true", "false")
160 # DIROUT1 Path to output directory.
161 # FILEOUT1 Path to output file.
162 # DIRIN1 Path to input directory.
163 # FILEIN1 Path to input file.
164 # OPTION_FILEOUT1_OVERWRITE Indicates whether file FILEOUT1 should be overwritten (ex: "true", "false')
165 # Script function dependencies:
166 # - echoerr Displays messages to stderr.
167 # - vbm Displays messsages to stderr if OPTION_VERBOSE set to "true".
168 # External dependencies: bash (5.0.3), echo
169 # Last modified: 2020-05-04T14:41Z
170 # Last modified by: Steven Baltakatei Sandoval
173 # [1]: Marco Aurelio (2014-05-08). "echo that outputs to stderr". https://stackoverflow.com/a/23550347
175 # Initialize function
176 #vbm "DEBUG:processArguments function called."
179 while [ ! $# -eq 0 ]; do # While number of arguments ($#) is not (!) equal to (-eq) zero (0).
180 #1>&2 echo "DEBUG:Starting processArguments while loop." # Debug stderr message. See [1].
181 #1>&2 echo "DEBUG:Provided arguments are:""$@" # Debug stderr message. See [1].
183 -h |
--help) showUsage
; exit 1;; # Display usage.
184 --version) showVersion
; exit 1;; # Show version
185 -v |
--verbose) OPTION_VERBOSE
="true"; vbm
"DEBUG:Verbose mode enabled.";; # Enable verbose mode. See [1].
186 -i |
--input-file) # Define input file path
187 if [ -f "$2" ]; then # If $2 is file that exists, set FILEIN1 to $2, pop $2.
190 vbm
"DEBUG:Input file FILEIN1 set to:""$2";
192 echoerr
"ERROR: Specified input file does not exist:""$2";
196 -I |
--input-dir) # Define input directory path
197 if [ -d "$2" ]; then # If $2 is dir that exists, set DIRIN1 to $2, pop $2.
200 vbm
"DEBUG:Input directory DIRIN1 set to:""$2";
201 else # Display error if $2 is not a valid dir.
202 echoerr
"ERROR:Specified input directory does not exist:""$2";
206 -o |
--output-file) # Define output file path
207 if [ -f "$2" ]; then # If $2 is file that exists, prompt user to continue to overwrite, set FILEOUT1 to $2, pop $2.
208 echoerr
"Specified output file $2 already exists. Overwrite? (y/n):"
210 y | Y |
yes) OPTION_FILEOUT1_OVERWRITE
="true";;
211 n | N | no
) OPTION_FILEOUT1_OVERWRITE
="false";;
212 *) echoerr
"Invalid selection. Exiting."; exit 1;;
214 if [ "$OPTION_FILEOUT1_OVERWRITE" == "true" ]; then
217 vbm
"DEBUG:Output file FILEOUT1 set to:""$2";
219 echoerr
"ERORR:Exiting in order to not overwrite output file:""$FILEOUT1";
225 vbm
"DEBUG:Output file FILEOUT1 set to:""$2";
227 -O |
--output-dir) # Define output directory path
228 if [ -d "$2" ]; then # If $2 is dir that exists, set DIROUT1 to $2, pop $2
231 vbm
"DEBUG:Output directory DIROUT1 set to:""$2";
233 echoerr
"ERROR:Specified output directory is not valid:""$2";
237 *) echoerr
"ERROR: Unrecognized argument."; exit 1;; # Handle unrecognized options. See [1].
243 vbm
"DEBUG:processArguments function ended."
244 return 0; # Function finished.
245 } # Evaluate script options from positional arguments (ex: $1, $2, $3, etc.).
247 # Usage: checkExecutables [ command1 ] [ command2 ] [...] [ commandN ]
248 # Description: Checks that provided commands exist and displays those that do not exist.
250 # - command names (arguments)
251 # Output: commands that don't exist (stderr)
252 # Script function dependencies:
253 # - echoerr for displaying errors via stderr
254 # - processArguments for setting OPTION_VERBOSE
255 # - vbm for displaying verbose messages if OPTION_VERBOSE is "true"
256 # External dependencies: bash (5.0.3), command
257 # Last modified: 2020-04-11T23:59Z
258 # Last modified by: Steven Baltakatei Sandoval
261 # [1]: SiegeX (2010-12-12). ["Difference between return and exit in Bash functions."](https://stackoverflow.com/a/4419971). Licensed CC BY-SA 4.0.
262 # [2]: Darryl Hein (2009-12-23). ["Add a new element to an array without specifying the index in Bash"](https://stackoverflow.com/a/1951523). Licensed CC BY-SA 4.0.
263 # [3]: kojiro (2012-10-03). ["Convert command line arguments into an array in Bash"](https://stackoverflow.com/a/12711853)
264 # [4]: niieani (2016-01-12). ["How to copy an array in Bash?"](https://stackoverflow.com/a/34733375/10850071). Licensed CC BY-SA 4.0.
266 # Initialize function
267 vbm
"DEBUG:checkExecutables function called."
268 declare -a candidateCommandsNames
# Initialize array for storing positional arguments provided to this function.
269 candidateCommandsNames
=("$@") # Save positional arguments to variable as string. See [3].
270 vbm
"DEBUG:candidateCommandsNames:""$@"
271 vbm
"DEBUG:candidateCommandsNames[0]:""${candidateCommandsNames[0]}"
272 vbm
"DEBUG:candidateCommandsNames[1]:""${candidateCommandsNames[1]}"
273 vbm
"DEBUG:candidateCommandsNames[2]:""${candidateCommandsNames[2]}"
274 declare -a outputInvalidCommandsArray
# Initialize arary for storing names of invalid commands.
275 declare -a outputValidCommandsArray
# Initialize array for storing names of valid commands.
278 for candidateCommandName
in "${candidateCommandsNames[@]}"; do # Search through all space-delimited text for valid commands.
279 if command -v "$candidateCommandName" 1>/dev
/null
2>/dev
/null
; then # Check if a command is valid or not.
280 outputValidCommandsArray
+=("$candidateCommandName") ; # See [2].
281 vbm
"DEBUG:Adding $candidateCommandName to outputValidCommandsArray."
283 outputInvalidCommandsArray
+=("$candidateCommandName") ; # See [2].
284 vbm
"DEBUG:Adding $candidateCommandName to outputInvalidCommandsArray."
289 if [ ${#outputInvalidCommandsArray[@]} -gt 0 ]; then # if number of elements in outputInvalidCommandsArray greater than 0, then display offending commands and exit 1.
290 echoerr
"ERROR: Invalid commands found:""${outputInvalidCommandsArray[@]}"; # display invalid commands as error
292 elif [ ${#outputInvalidCommandsArray[@]} -eq 0 ]; then # if number of elements in outputInvalidCommandsArray equals zero, then return 0.
293 vbm
"DEBUG: Valid commands are:""${outputValidCommandsArray[@]}"; # display valid commands if verbose mode enabled
296 echoerr
"ERROR: Check outputInvalidCommandsArray.";
300 vbm
"DEBUG:checkExecutables function ended."
301 return 0; # Function finished.
302 } # Check that certain executables exist.
303 updateTimeConstants
() {
304 # Usage: updateTimeConstants
305 # Description: Updates time-related variables for use by other scripts.
307 # Output: Sets following variables:
308 # TIME_CURRENT Current time in long ISO-8601 format. (ex: YYYY-mm-ddTHH:MM:SS+ZZZZ)
309 # TIME_CURRENT_SHORT Current time in short ISO-8601 format. (ex: YYYYmmddTHHMMSS+ZZZZ)
310 # DATE_CURRENT Current date in ISO-8601 format. (ex: YYYY-mm-dd)
311 # DATE_CURRENT_SHORT Current date in short ISO-8601 format. (ex: YYYYmmdd)
312 # DATE_TOMORROW Tomorrow's date in ISO-8601 format. (ex: YYYY-mm-dd)
313 # TIME_NEXT_MIDNIGHT Time of tomorrow's midnight in long (ex: YYYY-mm-ddTHH:MM:SS+ZZZZ)
315 # SEC_TIL_MIDNIGHT Seconds until next midnight.
316 # Script function dependencies:
317 # - echoerr for displaying errors via stderr
318 # - processArguments for setting OPTION_VERBOSE
319 # - vbm for displaying verbose messages if OPTION_VERBOSE is "true"
320 # External dependencies: bash (5.0.3), date, echo
321 # Last modified: 2020-04-11T23:59Z
322 # Last modified by: Steven Baltakatei Sandoval
326 # Initialize function
327 vbm
"DEBUG:updateTimeConstants function called."
330 TIME_CURRENT
="$(date --iso-8601=seconds)" ;
331 TIME_CURRENT_SHORT
="$(date -d "$TIME_CURRENT" +%Y%m%dT%H%M%S%z)"
332 DATE_CURRENT
="$(date -d "$TIME_CURRENT" --iso-8601=date)" ;
333 DATE_CURRENT_SHORT
="$(date -d "$TIME_CURRENT" +%Y%m%d)" ;
334 DATE_TOMORROW
="$(date -d "$TIME_CURRENT next day
" --iso-8601=date)" ;
335 TIME_NEXT_MIDNIGHT
="$(date -d "$DATE_TOMORROW" --iso-8601=seconds)" ;
336 SECONDS_UNTIL_NEXT_MIDNIGHT
="$(( $(date +%s -d "$TIME_NEXT_MIDNIGHT") - $(date +%s -d "$TIME_CURRENT") ))" ;
339 vbm
"DEBUG:updateTimeConstants function ended."
340 return 0; # Function finished.
341 } # Update time constants
343 #== Main Program Definition ==
345 # Usage: main "$@" # See [1].
346 # Input: unspecified (note: all Global Constants declared at beginning of script assumed to be available)
347 # OPTION_VERBOSE (used by vbm, set by processArguments) (ex: "true", "false")
348 # Output: unspecified
349 # Script function dependencies:
350 # - echoerr for displaying errors via stderr
351 # - vbm for displaying verbose messages if OPTION_VERBOSE is "true"
352 # - processArguments for setting OPTION_VERBOSE
353 # - checkExecutables for checking that specified commands are available
354 # External dependencies: bash (5.0.3), echo
355 # Last modified: 2020-05-04T16:50Z
356 # Last modified by: Steven Baltakatei Sandoval
359 # [1]: ErichBSchulz (2011-11-20). [How to correctly pass bash script arguments to functions](https://stackoverflow.com/a/8198970). Licensed CC BY-SA 4.0.
361 # Initialize function
362 processArguments
"$@" # Process arguments.
363 vbm
"DEBUG:main function called."
364 vbm
"DEBUG:main function arguments are:""$@"
365 checkExecutables
"echo" "date" "cut" "awk" # Confirm that executables necessary to run are available. Exit if any fail.
368 if [ -v FILEIN1
]; then # VERBOSE: Display contents of FILEIN1 if FILEIN1 has been set.
369 vbm
"DEBUG:main function detects input file:""$FILEIN1" ;
370 vbm
"DEBUG:contents of following file is displayed below:""$FILEIN1" ;
371 if [ "$OPTION_VERBOSE" == "true" ]; then # display FILEIN1 contents via cat if verbose mode specified
372 echoerr
"========""$FILEIN1"" START""========" ;
373 cat "$FILEIN1" 1>&2 ;
374 echoerr
"========""$FILEIN1"" END""========" ;
379 OUTPUT
="$OUTPUT""Hello world.\n"
380 if [ -v FILEIN1
]; then
381 OUTPUT
="$OUTPUT""The b2sum hash of $FILEIN1 is: $(b2sum "$FILEIN1" | awk '{print $1}').\n";
383 OUTPUT
="$OUTPUT""The current time is:""$SCRIPT_TIME_SHORT\n"
388 if [ -v FILEOUT1
]; then # if FILEOUT1 set, write to this file.
389 vbm
"DEBUG:main function detects output file:""$FILEOUT1" ;
390 echo -e "$OUTPUT" > "$FILEOUT1" ;
391 vbm
"DEBUG:main funtion wrote OUTPUT to:""$FILEOUT1" ;
392 elif [ -v DIROUT1
]; then # else if DIROUT1 set, set FILEOUT1 to timestamped filename, combine into PATHOUT1, write output to PATHOUT1.
393 vbm
"DEBUG:main function detects output directory:""$DIROUT1" ;
394 FILEOUT1
="$SCRIPT_TIME_SHORT"..output
395 PATHOUT1
="$DIROUT1"/"$FILEOUT1"
396 echo -e "$OUTPUT" > $PATHOUT1 ;
397 vbm
"DEBUG:main function wrote output file to:""$PATHOUT1" ;
401 vbm
"DEBUG:main function ended."
402 return 0; # Function finished.
405 #== Perform work and exit ==
406 main
"$@" # Run main function.