Published on

TIL: piping into tail hides a failed command

TIL: piping into tail hides a failed command
Authors

The script said "pushed". The push had been rejected.

Here's the script. It pushed a branch and trimmed the noisy output:

git push origin my-branch | tail -3
echo "pushed"

The catch: a pipeline's exit status is the status of its last command. git push failed, tail succeeded, so the whole line counted as a success.

You can see it in one line:

false | tail -1; echo $?
# 0

set -o pipefail
false | tail -1; echo $?
# 1
Two terminal panels: without pipefail, false piped into tail exits 0; with set -o pipefail, the same line exits 1.

I ran both in bash. Without pipefail, the failure disappears. With it, the pipeline returns a non-zero status if any command in it failed.

Two ways to fix it

  • Put set -o pipefail at the top of the script (and set -e if you want it to stop).
  • Don't pipe a command whose success you need to check. Run git push on its own and print the tail of its log separately.

I hit this while debugging an automation that kept reporting stale state after a push that had failed. The command was never the problem. The pipe hid it.