Stop your bash scripts from dying mid-run because of one bad exit code

Shell Scripting / Bash Tricks

Stop your bash scripts from dying mid-run because of one bad exit code

🧩 The Challenge

We have all written a script that blindly executes a sequence of commands, only to realize the third command failed silently and the fourth command just nuked a production directory because the variables weren’t set. It is infuriating to debug these cascading failures after the damage is already done.

💡 The Fix

Flip the set -e and -u switches at the top of your scripts to force bash to bail out the moment anything goes sideways or you try to access a variable you forgot to define. It saves you from yourself every single time.

#!/usr/bin/env bash
set -euo pipefail

⚙️ Why It Works

Setting -e stops execution on non-zero exits, -u hits you with an error if you reference an unset variable, and -o pipefail makes sure that if any command in a pipe chain fails, the whole pipeline registers as a failure rather than just the last one.

🚀 Pro-Tip: Add -x if you are really stuck, but prepare for a wall of text that will reveal exactly which line is failing.

Linux Tips & Tricks | © ngelinux.com | 8/19/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted