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.

exiter(){
 case $1 in
  1)
   echo You must be root to run this script
  ;;
  2)
   echo You specified a file that does not exist
  ;;
  3)
   echo This is yet another error message
  ;;
 esac
 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.