| 1 | #!/bin/bash |
| 2 | |
| 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 ). |
| 6 | |
| 7 | #== Variable Initialization == |
| 8 | |
| 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. |
| 17 | |
| 18 | #== Function Definitions == |
| 19 | |
| 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 $*"; } |
| 25 | |
| 26 | |
| 27 | echoerr() { |
| 28 | # Usage: echo [ arguments ] |
| 29 | # Description: Prints provided arguments to stderr. |
| 30 | # Input: unspecified |
| 31 | # Output: 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 |
| 36 | # License: GPLv3+ |
| 37 | # Ref./Attrib: |
| 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. |
| 39 | |
| 40 | echo "$@" 1>&2; # Define stderr echo function. See [1]. |
| 41 | return 0; # Function finished. |
| 42 | } # Define stderr message function. |
| 43 | vbm() { |
| 44 | # Usage: vbm "DEBUG:verbose message here" |
| 45 | # Description: Prints verbose message ("vbm") to stderr if OPTION_VERBOSE is set to "true". |
| 46 | # Input: |
| 47 | # - OPTION_VERBOSE variable set by processArguments function. (ex: "true", "false") |
| 48 | # - "$@" positional arguments fed to this function. |
| 49 | # Output: stderr |
| 50 | # Script function dependencies: echoerr |
| 51 | # External function dependencies: echo |
| 52 | # Last modified: 2020-04-11T23:57Z |
| 53 | # Last modified by: Steven Baltakatei Sandoval |
| 54 | # License: GPLv3+ |
| 55 | # Ref./Attrib: |
| 56 | |
| 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. |
| 60 | fi |
| 61 | |
| 62 | # End function |
| 63 | return 0; # Function finished. |
| 64 | } # Verbose message display function. |
| 65 | run() { |
| 66 | # Usage: run [cmd] |
| 67 | # Description: Runs command; reports success if command exit code 0; exits otherwise. |
| 68 | # Input: none |
| 69 | # Output: stdout |
| 70 | # Script function dependencies: none |
| 71 | # Last modified: 2020-06-19T22:09Z |
| 72 | # Last modified by: Steven Baltakatei Sandoval |
| 73 | # License: GPLv3+ |
| 74 | # Ref.Attrib: https://stackoverflow.com/a/18880585 |
| 75 | cmd_output=$(eval $1) |
| 76 | return_value=$? |
| 77 | if [ $return_value != 0 ]; then |
| 78 | echo "Command $1 failed"; |
| 79 | exit -1; |
| 80 | else |
| 81 | echo "output: $cmd_output"; |
| 82 | echo "Command succeeded."; |
| 83 | fi |
| 84 | return $return_value |
| 85 | } # |
| 86 | showUsage() { |
| 87 | # Usage: showUsage |
| 88 | # Description: Displays script usage information. |
| 89 | # Input: none |
| 90 | # Output: stderr |
| 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 |
| 95 | # License: GPLv3+ |
| 96 | # Ref./Attrib.: |
| 97 | |
| 98 | echoerr "USAGE:" |
| 99 | echoerr " bktemplate.sh [ options ]" |
| 100 | echoerr |
| 101 | echoerr "OPTIONS:" |
| 102 | echoerr " -h, --help" |
| 103 | echoerr " Display help information." |
| 104 | echoerr |
| 105 | echoerr " --version" |
| 106 | echoerr " Display script version." |
| 107 | echoerr |
| 108 | echoerr " -v, --verbose" |
| 109 | echoerr " Display debugging info." |
| 110 | echoerr |
| 111 | echoerr " -o, --output-file [ file ]" |
| 112 | echoerr " Specify output file." |
| 113 | echoerr |
| 114 | echoerr " -i, --input-file [ file ]" |
| 115 | echoerr " Specify input file." |
| 116 | echoerr |
| 117 | echoerr " -o, --output-dir [ directory ]" |
| 118 | echoerr " Specify output directory." |
| 119 | echoerr |
| 120 | echoerr " -i, --input-dir [ directory ]" |
| 121 | echoerr " Specify input directory." |
| 122 | echoerr |
| 123 | |
| 124 | # End function |
| 125 | return 0; # Function finished. |
| 126 | } # Display information on how to use this script. |
| 127 | showVersion() { |
| 128 | # Usage: showVersion |
| 129 | # Descriptoin: Displays script version and license information. |
| 130 | # Input: unspecified |
| 131 | # Output: stderr |
| 132 | # Script function dependencies: echoerr |
| 133 | # External function dependencies: echo |
| 134 | # Last modified: 2020-04-11T23:57Z |
| 135 | # Last modified by: Steven Baltakatei Sandoval |
| 136 | # License: GPLv3+ |
| 137 | # Ref./Attrib: |
| 138 | |
| 139 | # Initialize function |
| 140 | vbm "DEBUG:showVersion function called." |
| 141 | |
| 142 | # Perform work |
| 143 | OUTPUT="$SCRIPT_VERSION" |
| 144 | |
| 145 | # Display results |
| 146 | echoerr "$OUTPUT"; |
| 147 | |
| 148 | # End function |
| 149 | vbm "DEBUG:showVersion function ended." |
| 150 | return 0; # Function finished. |
| 151 | } # Display script version. |
| 152 | processArguments() { |
| 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 |
| 171 | # License: GPLv3+ |
| 172 | # Ref./Attrib.: |
| 173 | # [1]: Marco Aurelio (2014-05-08). "echo that outputs to stderr". https://stackoverflow.com/a/23550347 |
| 174 | |
| 175 | # Initialize function |
| 176 | #vbm "DEBUG:processArguments function called." |
| 177 | |
| 178 | # Perform work |
| 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]. |
| 182 | case "$1" in |
| 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. |
| 188 | FILEIN1="$2"; |
| 189 | shift; |
| 190 | vbm "DEBUG:Input file FILEIN1 set to:""$2"; |
| 191 | else |
| 192 | echoerr "ERROR: Specified input file does not exist:""$2"; |
| 193 | echoerr "Exiting."; |
| 194 | exit 1; |
| 195 | fi ;; |
| 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. |
| 198 | DIRIN1="$2"; |
| 199 | shift; |
| 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"; |
| 203 | echoerr "Exiting."; |
| 204 | exit 1; |
| 205 | fi ;; |
| 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):" |
| 209 | read m; case $m in |
| 210 | y | Y | yes) OPTION_FILEOUT1_OVERWRITE="true";; |
| 211 | n | N | no) OPTION_FILEOUT1_OVERWRITE="false";; |
| 212 | *) echoerr "Invalid selection. Exiting."; exit 1;; |
| 213 | esac |
| 214 | if [ "$OPTION_FILEOUT1_OVERWRITE" == "true" ]; then |
| 215 | FILEOUT1="$2"; |
| 216 | shift; |
| 217 | vbm "DEBUG:Output file FILEOUT1 set to:""$2"; |
| 218 | else |
| 219 | echoerr "ERORR:Exiting in order to not overwrite output file:""$FILEOUT1"; |
| 220 | exit 1; |
| 221 | fi |
| 222 | else |
| 223 | FILEOUT1="$2"; |
| 224 | shift; |
| 225 | vbm "DEBUG:Output file FILEOUT1 set to:""$2"; |
| 226 | fi ;; |
| 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 |
| 229 | DIROUT1="$2"; |
| 230 | shift; |
| 231 | vbm "DEBUG:Output directory DIROUT1 set to:""$2"; |
| 232 | else |
| 233 | echoerr "ERROR:Specified output directory is not valid:""$2"; |
| 234 | echoerr "Exiting."; |
| 235 | exit 1; |
| 236 | fi ;; |
| 237 | *) echoerr "ERROR: Unrecognized argument."; exit 1;; # Handle unrecognized options. See [1]. |
| 238 | esac |
| 239 | shift |
| 240 | done |
| 241 | |
| 242 | # End function |
| 243 | vbm "DEBUG:processArguments function ended." |
| 244 | return 0; # Function finished. |
| 245 | } # Evaluate script options from positional arguments (ex: $1, $2, $3, etc.). |
| 246 | checkExecutables() { |
| 247 | # Usage: checkExecutables [ command1 ] [ command2 ] [...] [ commandN ] |
| 248 | # Description: Checks that provided commands exist and displays those that do not exist. |
| 249 | # Input: |
| 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 |
| 259 | # License: GPLv3+ |
| 260 | # Ref./Attrib.: |
| 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. |
| 265 | |
| 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. |
| 276 | |
| 277 | # Perform work |
| 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." |
| 282 | else |
| 283 | outputInvalidCommandsArray+=("$candidateCommandName") ; # See [2]. |
| 284 | vbm "DEBUG:Adding $candidateCommandName to outputInvalidCommandsArray." |
| 285 | fi |
| 286 | done |
| 287 | |
| 288 | # Output results |
| 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 |
| 291 | exit 1; # See [1]. |
| 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 |
| 294 | return 0; # See [1]. |
| 295 | else |
| 296 | echoerr "ERROR: Check outputInvalidCommandsArray."; |
| 297 | fi |
| 298 | |
| 299 | # End function |
| 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. |
| 306 | # Input: (none) |
| 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) |
| 314 | # ISO-861 format. |
| 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 |
| 323 | # License: GPLv3+ |
| 324 | # Ref./Attrib.: |
| 325 | |
| 326 | # Initialize function |
| 327 | vbm "DEBUG:updateTimeConstants function called." |
| 328 | |
| 329 | # Perform work |
| 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") ))" ; |
| 337 | |
| 338 | # End function |
| 339 | vbm "DEBUG:updateTimeConstants function ended." |
| 340 | return 0; # Function finished. |
| 341 | } # Update time constants |
| 342 | |
| 343 | #== Main Program Definition == |
| 344 | main() { |
| 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 |
| 357 | # License: GPLv3+ |
| 358 | # Ref./Attrib.: |
| 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. |
| 360 | |
| 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. |
| 366 | |
| 367 | # Process inputs |
| 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""========" ; |
| 375 | fi |
| 376 | fi |
| 377 | |
| 378 | # Perform work |
| 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"; |
| 382 | fi |
| 383 | OUTPUT="$OUTPUT""The current time is:""$SCRIPT_TIME_SHORT\n" |
| 384 | |
| 385 | # Output results |
| 386 | echo -e "$OUTPUT" |
| 387 | |
| 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" ; |
| 398 | fi |
| 399 | |
| 400 | # End function |
| 401 | vbm "DEBUG:main function ended." |
| 402 | return 0; # Function finished. |
| 403 | } |
| 404 | |
| 405 | #== Perform work and exit == |
| 406 | main "$@" # Run main function. |
| 407 | exit 0; |