December 1, 2026
Bash terminal showing pipefail command

Bash pipefail prevents silent failures in pipelines. Without it, only the last command’s exit code matters, so a failed grep in the middle of a pipeline goes unnoticed. This guide shows how to use set -o pipefail and why it matters for production scripts.

The silent pipeline problem

A Bash pipeline runs multiple commands connected by pipes. By default, Bash only checks the exit code of the last command in the pipeline. Every command before it can fail silently, and the script continues as if nothing happened.

Consider this common scenario:


grep "ERROR" /var/log/app.log | awk '{print }' | sort | uniq -c

If the log file does not exist, grep fails. But because awk, sort, and uniq all succeed with empty input, the pipeline’s exit code is 0. Your script thinks everything worked when it actually processed nothing.

What pipefail does

Adding set -o pipefail changes the behavior. The pipeline’s exit code becomes the exit code of the rightmost command that failed, or 0 if all commands succeeded.


#!/bin/bash
set -o pipefail

grep "ERROR" /var/log/app.log | awk '{print }' | sort | uniq -c
echo "Exit code: $?"

Now if grep fails because the file is missing, the pipeline returns grep’s non-zero exit code, and you can catch it:


#!/bin/bash
set -o pipefail

if ! grep "ERROR" /var/log/app.log | awk '{print }' | sort | uniq -c; then
    echo "Pipeline failed, investigating..."
    exit 1
fi

Combining pipefail with set -e

pipefail works best with set -e, which exits the script immediately when any command fails. Together they catch failures early instead of letting bad data flow downstream.


#!/bin/bash
set -euo pipefail

The -u flag also exits on unset variables, which prevents silent data corruption from missing environment variables.

When pipefail changes behavior

Scenario Without pipefail With pipefail
grep finds no matches Exit 0 (grep returns 1, but last command succeeds) Exit 1 (grep failure propagates)
Middle command fails Exit 0 if last command succeeds Exit code of the failing command
All commands succeed Exit 0 Exit 0

Common gotchas

Commands that intentionally return non-zero

Some commands return non-zero as part of normal operation. grep returns 1 when no match is found, which is not necessarily an error. Wrap those commands explicitly when you want to allow the failure:


#!/bin/bash
set -o pipefail

grep "WARNING" /var/log/app.log || true | awk '{print $1}'

The || true converts grep’s exit 1 to exit 0, so pipefail does not treat a missing match as a pipeline failure.

Pipes inside conditionals

pipefail works inside if statements too:


if grep "ERROR" /var/log/app.log | grep -v "expected" | head -5; then
    echo "Unexpected errors found"
fi

Useful DevStackIO Tools

Validate and debug your Bash scripts and JSON/YAML output with our free tools:

Related Reading

Leave a Reply

Your email address will not be published. Required fields are marked *