Stop getting burned when your shell script swallows the exit code
Technical Briefing | 12/4/2026
We have all been there. You write a script, throw in a pipeline, and assume that if the middle command dies, the whole thing exits. But bash is sneakier than that. Unless you explicitly tell it to care about the status of every single part of a pipe, it only looks at the exit code of the final command. That is how you end up with a log file full of empty data because your grep command failed but the redirector kept running regardless.
Why the pipe operator is not as safe as you think
When you chain commands like cat file | grep match | wc -l, the exit status of the entire line is just the status of the final command. If the grep fails, the shell does not care. It only reports success if wc completes. This bit me in prod once during a log rotation job where a failed find command still triggered an empty tar archive because the shell kept moving on.
set -o pipefail
find /var/logs -name '*.log' | xargs tar -czf backup.tar.gz
- pipefail forces the shell to return the exit status of the last command to exit with a non-zero status in the pipe
- If you do not set this, you are effectively running blind when your data streams break mid-pipe
- Put this at the very top of your script right next to your set -e and set -u settings
You might think using set -e is enough, but it only catches the exit status of simple commands. It does not look inside pipes unless you combine it with pipefail. If you have an existing script, add the pipefail option immediately. It is a tiny change that prevents massive headaches when you least expect them.
