brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: set -o pipefail makes a pipeline fail when any part of it fails

Shell
~/tips/tip-shell-set-pipefail

set -o pipefail

Makes a pipeline report failure when any command in it fails, not only the last one.

A pipeline normally reports only the exit status of its last command. That means the first half can blow up and your script cheerfully carries on.

Turn on pipefail and the pipeline returns the status of the rightmost command that failed, or zero if all of them succeeded. The manual says exactly that. It changes what $? holds and what set -e reacts to.

$ false | true; echo $?
0
$ set -o pipefail
$ false | true; echo $?
1

Think of pg_dump db | gzip > backup.gz. If the dump fails halfway, gzip is still happy and exits with 0. Without pipefail your backup script reports success on a broken file.

Caveats, and there are a few. The status is only the last failing command, so you do not see which one broke. Some commands exit non-zero on purpose: grep returns 1 when nothing matches, and with pipefail that makes grep foo file | wc -l a failure. Add || true where you expect that. Also, pipefail is not in plain POSIX sh, so it belongs in scripts that start with a Bash shebang.

Further reading: Bash manual: Pipelines, Bash manual: The Set Builtin, On this site: trap EXIT cleans up your temp files, even when the script dies, On this site: ${var:?} stops a script before an empty variable eats your files

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link