Practical Bazel: Enable Bash Strict Mode
Practical Bazel bazel bash
Published: 2020-10-30
Practical Bazel: Enable Bash Strict Mode

One tends to write a lot of Bash scripts when using Bazel. In order to make these scripts more robust, enable Bash’s unofficial strict mode by starting all scripts like this:

1
2
3
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

When debugging a script, I often add an extra set -x in the script header and then remove it before submitting the pull request.

There are a few commonly-encountered issues when enabling strict mode, many of which are covered by the unofficial strict mode blog post. The one I run into the most is “How do you detect if an environment variable is set without tripping over the ‘unreferenced variable’ error”? Since I use Bash versions >= 4.2 everywhere, I prefer the -v operator, as in:

1
2
3
4
5
6
7
if [[ ! -v ENV_VAR ]]; then
  echo "ENV_VAR is not set"
elif [[ -z "$ENV_VAR" ]]; then
  echo "ENV_VAR is set to the empty string"
else
  echo "ENV_VAR has the value: $ENV_VAR"
fi