Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A Bash pipeline normally reports the exit status of its last command. Therefore, if an earlier command fails but the final command completes successfully, $? is 0 even though the producer failed. Enable pipefail when you need one pipeline status that reflects component failures, or read Bash’s PIPESTATUS array when you need every command’s status.

What the zero actually means

A pipeline connects the standard output of one command to the standard input of the next. In this example, producer writes data and formatter reads it:

producer | formatter
status=$?

In Bash, status is the status Bash assigned to the whole pipeline. By default, that is the status returned by formatter, the command on the right. The GNU Bash Reference Manual states: “The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled.” See the Bash pipelines documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Consequently, this pipeline can print 0:

sh -c 'printf "%sn" "producer failed" >&2; exit 7' | cat
printf 'pipeline status: %sn' "$?"

The first command exits 7. cat receives no useful input, nevertheless exits successfully after reaching end-of-file. Because cat is last, the pipeline status is 0. The zero says only that the final command succeeded under the shell’s default status rule; it does not prove that every command in the pipeline succeeded.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How to see the masking behavior safely

A minimal demonstration

bash -c 'false | true; printf "status=%sn" "$?"'

This prints status=0. false deliberately returns a nonzero status, while true returns zero. Bash chooses the latter for the pipeline.

Why assigning $? later does not help

$? always refers to the most recently completed command or pipeline as the shell calculated it. In the following sequence, the assignment captures the pipeline result, not the producer’s result:

producer | formatter
status=$?

Adding an echo, assignment, or another command before capturing status can also replace the status information you intended to inspect. Decide whether you need one combined result or individual results, then capture the appropriate value immediately.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use pipefail for a reliable combined result

Enable it for the current Bash shell

set -o pipefail
producer | formatter
status=$?
printf 'pipeline status: %sn' "$status"

With pipefail enabled, Bash returns the status of the rightmost command in the pipeline that exited nonzero. If every command succeeds, the pipeline status is zero. In the demonstration above, the pipeline becomes nonzero because the producer exits 7 and the consumer exits 0; the resulting status is 7.

pipefail changes status selection only. It does not terminate a script by itself. Handle the nonzero result explicitly:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
set -o pipefail
if producer | formatter; then
    printf '%sn' 'pipeline completed successfully'
else
    status=$?
    printf 'pipeline failed with status %sn' "$status" >&2
    exit "$status"
fi

Using the pipeline directly as an if condition lets Bash test the combined result without an intervening command. If the pipeline fails, the else branch can log, clean up, retry, or exit according to the script’s requirements.

Make the setting visible in scripts

Place the option near the start of a Bash script when all later pipelines should use failure-aware status selection:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#!/usr/bin/env bash
set -o pipefail

You can verify the option in a running Bash session with set -o; the line for pipefail shows whether it is enabled. Scope the decision deliberately: a script that relies on the default “last command wins” behavior may change its control flow when pipefail is turned on.

Read every component with Bash’s PIPESTATUS

Sometimes a single pipeline result is not enough. You may need to know whether the producer failed, whether the formatter failed, or whether both did. Bash provides the PIPESTATUS array, which contains the status of each command in the most recently executed foreground pipeline. The array is documented in the GNU Bash Reference Manual.

Capture it immediately

producer | formatter
pipeline_statuses=("${PIPESTATUS[@]}")
printf 'producer=%s formatter=%sn' 
    "${pipeline_statuses[0]}" "${pipeline_statuses[1]}"

The copy operation must be the first thing you do after the pipeline. Running printf, echo, another pipeline, or another command before copying the array can replace its contents. Once copied, the values are safe to inspect, log, or test later.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Check a particular element

producer | formatter
statuses=("${PIPESTATUS[@]}" )

if (( statuses[0] != 0 )); then
    printf 'producer failed with %sn' "${statuses[0]}" >&2
fi
if (( statuses[1] != 0 )); then
    printf 'formatter failed with %sn' "${statuses[1]}" >&2
fi

Array index 0 corresponds to the leftmost command, index 1 to the next command, and so on. The number of useful elements depends on how many commands are in the pipeline.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preserve statuses and return an appropriate result

producer | formatter
statuses=("${PIPESTATUS[@]}" )

for status in "${statuses[@]}"; do
    if (( status != 0 )); then
        printf 'pipeline component failed: %sn' "$status" >&2
        exit "$status"
    fi
done

This example returns the first nonzero value it encounters in the saved array. That policy is different from Bash’s pipefail policy, which selects the rightmost nonzero status. Choose the rule that matches your caller’s expectations, and document it if the exact code matters.

Choose between pipefail and PIPESTATUS

Need Use What you receive Important limitation
One status for the whole pipeline set -o pipefail Zero only when all commands succeed; otherwise the rightmost nonzero status It reports a failure but does not stop the script automatically
The status of every pipeline command PIPESTATUS An array with one status per command in the most recent foreground pipeline Bash-specific; copy it before executing another command
Both a combined result and diagnostics Enable pipefail and immediately copy PIPESTATUS A pipeline-level status plus each component’s exact status You still must decide how to log, retry, or terminate

For a short script that only needs to reject an incomplete pipeline, pipefail is usually the clearest choice. For monitoring, diagnostics, or recovery that depends on the failed stage, capture PIPESTATUS. These mechanisms complement each other rather than solving the same problem.

Do not confuse failure reporting with script termination

A nonzero pipeline status is information. Your script must decide what that information means. Typical responses include returning the status to a caller, printing an actionable error, attempting a retry, or continuing when a particular stage is optional.

set -o pipefail

if ! producer | formatter; then
    status=$?
    printf 'required pipeline failed: %sn' "$status" >&2
    exit "$status"
fi

When using !, remember that the condition itself is logically inverted. If you need the original nonzero status for logging, structure the test so that you capture it directly in an else branch, as in the earlier example. Do not assume that enabling pipefail is equivalent to enabling an “exit on error” policy; they are separate decisions and should be reviewed separately in scripts with complex conditionals or intentionally tolerated failures.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Portability: identify the shell before copying the fix

The behavior described here is grounded in Bash. POSIX specifies pipeline status in terms of the final command, but pipefail is not a universally portable POSIX assumption, and PIPESTATUS is a Bash-specific array. The POSIX.1-2024 Shell Command Language specification is the appropriate reference when a script must run under multiple shell implementations.

  • Confirm the interpreter from the shebang, such as #!/usr/bin/env bash, rather than assuming that an interactive Bash setting applies to a script launched by another shell.
  • Check the target shell’s documentation for support for pipefail before adding set -o pipefail.
  • Do not use PIPESTATUS in a script advertised as generic POSIX sh; it is not a portable interface.
  • If portability is more important than a shell-specific feature, design explicit status handling around the facilities available in each target shell and test the script under those interpreters.

A script can appear to work in an interactive Bash terminal and still fail when a scheduler, container entry point, or deployment system invokes it with a different shell. The interpreter is part of the program’s requirements.

Diagnose the component that actually failed

Once you expose the nonzero status, investigate that command rather than treating the pipeline’s final number as a root cause. An exit status is a shell-level signal; it does not explain whether the producer hit a missing file, invalid input, a network error, or another condition.

  1. Run the producer by itself. Redirect or inspect its standard error so the original diagnostic is visible.
  2. Run the consumer with controlled input. This separates a formatter or parser failure from an upstream data problem.
  3. Re-run the complete pipeline with pipefail. Confirm that the combined status changes as expected.
  4. Capture PIPESTATUS when more than one stage can fail. Record the array before logging any messages.
  5. Decide the policy for each status. A required producer may abort the job, while an optional reporting stage may be logged and ignored.

Keep diagnostic output on standard error when the pipeline’s standard output is data consumed by another command. Mixing logs into the data stream can create a second failure that obscures the first.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common mistakes and their corrections

Checking only $? after a default pipeline

Mistake: assuming a zero value proves every stage succeeded. Correction: enable pipefail before the pipeline or copy PIPESTATUS immediately afterward.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Capturing PIPESTATUS after a logging command

Mistake: running echo or printf first. Correction: assign statuses=("${PIPESTATUS[@]}" ) as the first command after the pipeline, then print the saved values.

Expecting pipefail to exit automatically

Mistake: enabling the option and assuming subsequent code cannot run. Correction: test the status with if, return it, or adopt a separately considered error-exit policy.

Copying Bash syntax into a POSIX shell

Mistake: using PIPESTATUS or assuming pipefail exists in every sh. Correction: pin the script to Bash when those features are required, or verify an alternative supported by the actual target shell.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical pattern for production scripts

The following pattern gives a required pipeline a single failure result while retaining per-command diagnostics:

#!/usr/bin/env bash
set -o pipefail

producer | formatter
statuses=("${PIPESTATUS[@]}" )

if (( statuses[0] != 0 || statuses[1] != 0 )); then
    printf 'producer status: %sn' "${statuses[0]}" >&2
    printf 'formatter status: %sn' "${statuses[1]}" >&2
    exit 1
fi

The explicit checks make the policy readable: either stage failing is a job failure, and the logs identify which stage returned nonzero. If callers need the exact rightmost nonzero value instead of the generic 1, calculate that from the saved array or rely on the pipeline result captured with pipefail.

For a simple pipeline where stage-level diagnostics are unnecessary, the shorter form is sufficient:

#!/usr/bin/env bash
set -o pipefail

if producer | formatter; then
    exit 0
fi
exit $?

Use the longer form when operators need to distinguish an upstream failure from a downstream failure. In every case, test the script with a deliberately failing producer and a successful consumer; that is the scenario that exposes the default masking behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Bottom line

The command did not “really” return zero merely because you observed zero through a pipe. Bash reported the status of the pipeline’s final command, and that successful consumer masked the earlier failure. In Bash, turn on set -o pipefail for a failure-aware combined status, or copy PIPESTATUS immediately after the pipeline when you need to identify every failing component. Confirm the shell implementation before relying on either feature.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.