Stop your scripts from ignoring exit codes in pipelines
By Saket Jain Published Linux/Unix
Stop your scripts from ignoring exit codes in pipelines
Technical Briefing | 10/28/2026
You probably think your pipeline is safe because you checked the exit code of the last command. But bash pipes hide everything except the final exit status by default. If your first command in a three-stage pipe fails silently, the script keeps running as if nothing happened. I have spent far too many hours debugging production data corruption because a gzip failure was swallowed by a grep, leaving me with a half-processed output file.
Pipefail is the bare minimum
The most common mistake is forgetting that pipelines act as a single command. If you do not explicitly tell the shell to care about intermediate failures, it simply takes the status of the rightmost process. Setting the pipefail option changes this behavior so the pipeline returns the exit status of the last command to exit with a non-zero code. This bit me in prod back when I was junior, and I still see it in legacy scripts all the time.
set -o pipefail
cat data.log | grep "ERROR" | cut -d' ' -f2 > errors.txt
[[ $? -eq 0 ]] || echo "Pipeline failed, check your input files"
- Use set -o pipefail at the very top of every script.
- Remember that local variables in functions do not automatically inherit shell options.
- Check your environment, as some older shells might not support this flag reliably.
If you really need to know which stage died, stop piping and use temporary files or process substitution. It is a bit more verbose, sure, but catching the failure at the point of origin saves you from the headache of cleaning up partial state later. Next time you write a heavy data pipeline, turn this on before you write the first line of logic.
