Stop your subshells from swallowing your exit codes
By Saket Jain Published Linux/Unix
Stop your subshells from swallowing your exit codes
Technical Briefing | 11/20/2026
You probably think your script stops when a command fails. Most of the time it does, especially if you have set -e enabled. But the moment you pipe output into a while loop or wrap a pipeline in a subshell, that exit code tracking silently vanishes. I have spent hours debugging scripts that blindly continued to ‘cleanup’ or ‘deploy’ steps because the pipeline fed into a loop masked a non-zero exit from the very command that was supposed to trigger the stop.
Why pipes are not your friends for error checking
When you use a pipe, the shell forks. Each part of that pipeline effectively runs in its own subshell. Even if the first command in your pipe fails hard, the shell only cares about the final command in the chain for the return status. This is why a malformed command piped into grep or awk will return a clean exit status of zero, leaving your script completely unaware that the data it is processing is garbage.
cat non_existent_file.txt | grep 'pattern' || echo 'This will trigger'
- Enable pipefail in bash to ensure the entire pipeline return status matches the last failed process
- Use process substitution when you need to read a command output into a loop without spawning a subshell
- Check PIPESTATUS array if you need to know exactly which component of the pipe failed
If you are writing anything beyond a trivial wrapper, set -o pipefail should be near the top of your script alongside set -eu. Without it, you are essentially writing code that ignores half of its own errors. Try running a simple command that fails inside a pipe without pipefail enabled, then check the return status; it will shock you how often your infrastructure relies on this silent failure mode to appear functional.
The next time you find a script that ran to completion despite corrupting a production config, check your pipes. Adding that one line to your shebang header is the cheapest insurance policy you will ever buy for your automation.
