Bash Strict Mode: Stop Silent Failures in Your Scripts 🧵
1/ Ever had a Bash script fail silently, leading to hours of debugging?
Bash doesn't fail by default—it keeps running even after errors. Here's how to fix it with strict mode. 👇
1/ Ever had a Bash script fail silently, leading to hours of debugging?
Bash doesn't fail by default—it keeps running even after errors. Here's how to fix it with strict mode. 👇
Comments
Adding three simple options to your script can prevent many hidden bugs:
set -euo pipefail
✔️ -e → Exit on error
✔️ -u → Treat unset variables as errors
✔️ -o pipefail → Catch pipeline failures
Normally, Bash ignores errors:
#!/bin/bash
false
echo "Still running"
🔹 The script continues running after false fails.
#!/bin/bash
set -e
false
echo "Never runs"
Unset variables can cause hard-to-debug issues:
echo "Hello, $USER_NAME" # Oops, typo: should be $USER
Without set -u, this runs without warning.
With set -u:
#!/bin/bash
set -u
echo "Hello, $USER_NAME"
❌ Error: USER_NAME is unset.
Pipelines hide errors by default:
false | echo "Ignored error"
echo "Script continues..."
🔹 Bash ignores the failure of false.
#!/bin/bash
set -o pipefail
false | echo "This will now fail"
🔴 The script stops immediately if any command in a pipeline fails.