Quick Tip
The `set -o pipefail` Secret for Bulletproof Scripts
Challenge: In shell scripting, if any command in a pipeline fails, the overall script might continue running as if nothing happened, leading to unexpected behavior and hard-to-debug errors. You need a way to ensure that a pipeline’s failure immediately signals a script failure.
The Solution: Use the `set -o pipefail` option at the beginning of your shell script.
#!/bin/bash set -o pipefail # Example pipeline ls -l | grep "some_file" | sort -r # If grep or sort fails, the script will exit immediately. # If set -o pipefail was NOT used, and grep failed (e.g., no "some_file" found), # sort might still run on an empty input, and the script would continue.
Why it works: When `set -o pipefail` is enabled, the exit status of a pipeline is the exit status of the last command in the pipeline that failed. If all commands in the pipeline succeed, the exit status is 0.
Pro-Tip: You can check the current state of `pipefail` with `set -o | grep pipefail`. To disable it, use `set +o pipefail`.
Linux Tips & Tricks | © ngelinux.com | 5/26/2026
