In this lesson, you will learn how to make your Bash scripts significantly more robust by enforcing "Strict Mode" to catch hidden bugs automatically.
Why "Strict Mode"?
By default, Bash is quite forgiving. If you reference a variable that doesn't exist, it simply assumes it is empty. If a command in a pipeline fails, Bash ignores the error and continues to the next command. This "silent failure" behavior is the leading cause of bugs in automation scripts. To fix this, we use the set command to enable specific shell options that force the script to stop immediately when things go wrong.
The Power of set -euo pipefail
The standard "Strict Mode" is implemented by adding this line at the very top of your script:
set -euo pipefail
Here is exactly what these flags do:
-e(errexit): The script will exit immediately if any command returns a non-zero status (i.e., fails). You no longer need to manually checkifstatements after every single line.-u(nounset): The script will exit if you try to use a variable that hasn't been defined yet. This prevents the common mistake of typo-ing a variable name and accidentally running a command with an empty argument.-o pipefail: In a normal pipe (e.g.,cmd1 | cmd2), Bash only looks at the exit code of the last command. Ifcmd1fails butcmd2succeeds, the pipe is considered a success. With this option, the entire pipe is treated as a failure if any part of it fails.
A Practical Example
Imagine you have a script that deletes files based on a variable:
#!/bin/bash
set -euo pipefail
rm -rf "/tmp/$TARGET_DIR/*"
Without strict mode, if $TARGET_DIR was never set, your script would try to run rm -rf /tmp/*, potentially deleting your entire temporary folder. With -u, the script stops before the rm command executes, protecting your system.
Key Takeaway: Adding set -euo pipefail at the start of your scripts turns Bash from a silent observer into a strict gatekeeper, catching errors the moment they occur.