Exit Strategy for BASH Scripts

For my more serious BASH scripts I like to have a predefined exit strategy layout at the top of the script, so it is easy to obtain the exit values along with make changes to the responses made by the script in different situations. Here’s how I do it.

 case $1 in
   echo You must be root to run this script
   echo You specified a file that does not exist
   echo This is yet another error message
 exit $1

And now all I need to do to give an error would be for example:

[[ -f $some_file ]] && echo 'tacos' >> $some_file || exiter 2

Nice, huh.

Leave a Reply

Your email address will not be published. Required fields are marked *