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: bash PIPESTATUS shows which part of a pipeline failed

Bash
~/tips/tip-shell-pipestatus-array

false | true | false

Reads the exit code of every command in the last pipeline, not only the final one.

A pipeline hands you one exit code, the one from the last command. If the download at the start fails but the filter at the end is happy, $? says 0 and you never hear about it. Bash keeps the other codes in an array, and I think it gets used far too little.

PIPESTATUS holds the exit status of every command in the most recently executed foreground pipeline, in order. You can see it with a pipeline that fails twice:

false | true | false
echo "${PIPESTATUS[@]}"
# 1 0 1

That makes it easy to check a single stage, for example a curl that feeds a jq:

curl -s https://example.com/data.json | jq '.items[]' > items.txt
if [ "${PIPESTATUS[0]}" -ne 0 ]; then echo "download failed"; fi

Here jq may well exit 0 on empty input, so the last status alone would not tell you anything went wrong. Index 0 is the first command, index 1 the second, and so on.

The catch is that bash sets the array again after every command, including simple ones. Even the [ test in the example above replaces it, so the second command in a line cannot read what the first left behind. If you need more than one value, copy the whole array first:

curl -s https://example.com/data.json | jq '.items[]' > items.txt
codes=("${PIPESTATUS[@]}")
echo "curl: ${codes[0]}, jq: ${codes[1]}"

It is bash only, so it does nothing in plain sh. If you do not care which stage failed and only want the pipeline to fail when any stage does, set -o pipefail is the simpler switch: the pipeline then returns the status of the rightmost command that failed.

Further reading: bash(1) manual page

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link