3 advices to write robust Bash scripts

To write robust Bash scripts, I recommend you to:

1. Activate the Bash options: errexit, nounset

Add these two options at the top of your BASH scripts:

  • errexit will stop your Bash script each time a command in your script returns an exit code different than “0”. It does not show any message when it quits, this is why it is important to show a traceback (check the second advice below “show a Bash traceback”).
  • nounset will stop your script and output an error if you attempt to use undefined variables. nounset is very important because it can avoid you to run dangerous commands like: rm –fr “/$undefinedvariable”

2. Show a Bash Traceback

Because the option “errexit” does not show any message when it stops your Bash script in some cases (for example var=$(yourcommand) will exit without any message, even when yourcommand returns an exit code different than zero), I recommend you to add the code below to show a traceback each time “errexit” forces your Bash script to stop:

The traceback will help you to know exactly which command in your Bash script exited with an error code different than “0”:

3. Check your Bash scripts with shellcheck and follow the recommendations of Advanced Bash-Scripting Guide.

Leave a Reply

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