Tuesday, February 11, 2025

Better Bash Scripting - Error Handling

 I was not aware of all the options you could set at the beginning of a script to help it be more reliable.

I have decided that my script will now have:

set -euo pipefail

The set -e is for the script to exit when there is an error (non-zero) execution of a line. This can come with some side effect but there are quick ways to adapt to them. You could do:

command_wit_error || true

To get your script to continue even if the command on the left did not complete with a zero.

The set -u is good to make sure all variables are set for the script to run properly. Reminds me of a strict mode in some other tools.

The set -o pipefail is good to make sure you get the error code of the rightmost command in the pipeline.

Quick reading on this topic because we have an error in a deployment script that did not prevent the rest to be attempted and cause other issues.