Bash Script Error Flag

Bash scripts can be very useful but also very tough to debug. Setting the correct error flag and understanding the behavior can help you out. Adding a flag of set -e tells the script to exit immediately if a command exits with an error status. From help set:

 -e  Exit immediately if a command exits with a non-zero status.

Adding a set +e is the default and if the script encounters an error it will output the error but continue with the script.

It should be noted that it is considered better practice to use a trap flag instead of set -e so you can call a custom function if a script encounters an error. This can be accomplished by:

trap 'handle_error' ERR

function handle_error() {
  # simply output the error
  echo $@
}

Read more about it here and a good read is BashFAQ. In addition this blog post has some really good info on other useful flags.

Instagram Post