Bash Strict Mode
In plain English: It tells the script to fail fast and crash immediately if something goes wrong, instead of blindly pressing on and potentially ruining your system.
set -euo pipefail
set -e (Exit on Error)
By default, Bash doesn’t care if a command fails; it will just move on to the next line. set -e changes that. If any command returns a non-zero exit code (which means it failed), the entire script stops immediately.
Without -e:
cd /folder_that_does_not_exist
rm -rf * # Yikes! Because the cd failed, you just deleted everything in your CURRENT directory.
With -e: The script crashes the second the cd command fails, saving your files.
set -u (Nounset / Unset Variables)
By default, if you reference a variable that hasn’t been defined, Bash treats it as an empty string and keeps going. set -u treats unset variables as an error and crashes the script.
Without -u:
TARGET_DIR=/tmp/my_app
# Imagine a typo happens below:
rm -rf "$TARGT_DIR/" # Because of the typo, this evaluates to `rm -rf /`
With -u: The script will halt and shout: TARGT_DIR: unbound variable, saving you from disaster.
set -o pipefail (Pipeline Failures)
This fixes a major blind spot with set -e. Normally, if you pipe commands together (cmd1 | cmd2), Bash only looks at the exit code of the last command (cmd2). If cmd1 fails but cmd2 succeeds, Bash thinks the whole line was a success.
-o pipefail ensures that if any command in a pipeline fails, the whole pipeline is considered a failure.
Without pipefail (even with -e):
mystatement_with_typo | grep "active"
# 'mystatement_with_typo' fails, but grep finds nothing and exits cleanly (or fails cleanly).
# The script continues because grep was the last command.
With pipefail: The script catches that the first command failed and stops.
When you see set -euo pipefail in a script, it is very often followed immediately by IFS=$‘\n\t’.
Together, they form the complete “Bash Strict Mode” boilerplate.
What is IFS?
IFS stands for Internal Field Separator. It is a special built-in variable that tells Bash how to recognize word boundaries when it is splitting strings (like loops or turning a string into an array). By default, Bash treats three characters as separators:
- space
- tab
- newline
What IFS=$‘\n\t’ Changes
By setting IFS=$‘\n\t’, you are removing the space from the list of separators. Now, Bash only splits strings when it hits a newline (\n) or a tab (\t).
Why the weird $” syntax?
If you just wrote IFS=‘\n\t’, Bash would literally look for the letter n and the letter t.
The $’…’ syntax is called ANSI-C Quoting. It tells Bash: “Hey, expand these backslash escapes into actual, literal tabs and newlines.”