How to Enable pipefail in Bash Scripts
In this tutorial, you'll learn about How to Enable pipefail in Bash Scripts. We cover key concepts, practical examples, and best practices.
The Problem
A Bash script that uses pipes continues running even when an earlier command in the pipe fails, because only the exit code of the last command in the pipeline is returned.
Quick Fix
Enable pipefail at the Top of the Script
set -o pipefail
false | echo "this succeeds"
echo "Exit code: $?"
Without pipefail, this exits 0 (success) because echo succeeds. With pipefail, the pipeline returns the exit code of false (1).
Combine pipefail with errexit
bash -c '
set -euo pipefail
false | echo "will not reach here"
echo "This line is never printed"
'
The combination set -euo pipefail is the standard hardening for Bash scripts. -e exits on any error, -u treats unset variables as errors, and -o pipefail propagates pipe failures.
Test pipefail Behavior
bash -c 'set -o pipefail; ls /nonexistent | head -1; echo "Exit: $?"'
# ls: cannot access /nonexistent: No such file or directory
# Exit: 2
With pipefail, the exit code 2 from ls (file not found) is propagated instead of being masked by head's success.
Disable pipefail for Specific Pipelines
bash -c '
set -o pipefail
! grep -q "error" log.txt | wc -l
echo "Ignoring pipe result: $?"
'
Prefixing a pipeline with ! inverts its exit code. Wrap specific commands in set +o pipefail / set -o pipefail if you need to opt out for a particular pipeline.
Debug Pipeline Failures with echo $PIPESTATUS
false | true | false
echo "${PIPESTATUS[@]}"
# 1 0 1
The PIPESTATUS array contains the exit codes of each command in the last pipeline. With pipefail, the pipeline returns the last non-zero value. Without it, you can inspect each element individually.
Use Debug Mode for Risky Operations
# See every command before it executes
bash -x risky_script.sh
# + sudo sed -i 's/old/new/' /etc/fstab
Always use debug mode when running scripts that modify system configuration like fstab, SELinux settings, or firewall rules. This shows every command before it executes, catching typos early.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Prevention
- Add
set -euo pipefailat the start of every Bash script for strict error handling - Test script behavior with intentional failures to ensure pipefail catches them
- Use
shellcheckto lint your scripts and flag missingpipefail - Document that your script requires Bash (not sh) since
pipefailis a Bash extension
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro