This is the sixth epidose of a small series.
Description:
Every command in a script may fail due to external reasons. Bash programming is not functional programming! 🙂
After running a command, make sure that you check the exit code and either raise a warning or exit with an error, depending on how a failure can impact the execution of the script.
BAD:
The worst example is not to check the exit code at all:
1 2 3 4 5 6 |
#!/bin/bash -l recover -a -f -c ${NWCLIENT} -d ${DEST_FILE_PATH} $BASEBCK_FILENAME # what if recover fails? do_something_with_recovered_files |
Next one is better, but you may have a lot of additional code to type:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/bin/bash -l recover -a -f -c ${NWCLIENT} -d ${DEST_FILE_PATH} $BASEBCK_FILENAME #--------- # the following piece of code is frequently copied&pasted ERR=$? if [ $ERR -ne 0 ] ; then # I've got an error with the recovery eerror "The recovery failed with exit code $ERR" Log_Close exit $ERR else eok "The recovery succeeded." fi #--------- do_something_with_recovered_files |
Again, Log_Close, eok, eerror, etc are functions defined using the previous Bash Tips & Tricks in this series.
GOOD:
Define once the check functions that you will use after every command:
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 |
# F_check_warn will eventually raise a warning but let the script continue function F_check_warn() { EXITCODE=$1 shift if [ $EXITCODE -eq 0 ] ; then eok $@ succeded with exit code $EXITCODE else ewarn $@ failed with exit code $EXITCODE. The script will continue. fi # return the same code so other checks can follow this one inside the script return $EXITCODE } # F_check_warn will eventually raise an error and exit function F_check_exit() { EXITCODE=$1 shift if [ $EXITCODE -eq 0 ] ; then eok $@ succeded with exit code $EXITCODE else eerror $@ failed with exit code $EXITCODE. The script will exit. Log_Close exit $EXITCODE fi } CMD="recover -a -f -c ${NWCLIENT} -d ${DEST_FILE_PATH} $BASEBCK_FILENAME" enotify "Recover command: $CMD" eval $CMD F_check_exit $? "Recovery from networker" do_something_with_the_recovered_files F_check_warn $? "Non-blocking operation with recovered files" |
The following two tabs change content below.
Latest posts by Ludovico (see all)
- New views in Oracle Data Guard 23c - January 3, 2024
- New in Data Guard 21c and 23c: Automatic preparation of the primary - December 22, 2023
- Does FLASHBACK QUERY work across incarnations or after a Data Guard failover? - December 13, 2023
Wow, I realize now that I have never rplied to your comment… Sorry Grzegorz.
I use shift get the rid of the first parameter, so that after that I can refer to $@ without caring about hte first parameter that was the exit code.
Thanks for the tips, could You explain why there is a shift in function ?
Regards
GG
Pingback: Bash tips & tricks [ep. 6]: Check the exit code - Ludovico Caldara - Blogs - triBLOG