Bash pipe swallows exit code when pipe like sed or tee [duplicate]
Asked Answered
T

1

0

I'm using turbo feature called turbo prune which creates folder out with partial copy of my monorepo, but unfortunately that means that when running in GitHub Actions commands like turbo run lint will print out paths that have out in them (thus breaking regular github error reporting), so I instead of having this command:

turbo run lint

I tried to replace it with:

turbo run lint | sed 's/\/out//g'

Which outputs correct paths, but my lint check always passes because even though turbo exited with exit code 1, but sed exited with 0.

Titoism answered 16/4 at 3:13 Comment(1)
If you dislike the answers on the other question, feel free to post your answer there instead. Creating a new duplicate is generally not the way to go.Maryannemarybella
T
0

TL;DR:

(set -o pipefail && <your command>)

The answer

I've been looking around SO and I found a few answers to this question. I will start with the shortest one, replace your turbo run lint | sed 's/\/out//g' with:

(set -o pipefail && turbo run lint | sed 's/\/out//g')

This will switch your shell into the mode where exit codes are no longer swallowed by pipe operator (just for this one command). If you do not mind switching your whole script into this mode you can skip using sub-shell and just do:

set -o pipefail 
turbo run lint | sed 's/\/out//g'

Now just for completeness you might also use something like this:

turbo run lint | sed 's/\/out//g'
exit ${PIPESTATUS[0]

And if you for some reason don't want to use sub shell but want to restore default handling of exit codes in pipes you can use this solution:

set -o pipefail 
turbo run lint | sed 's/\/out//g'
set +o pipefail 

There are even more exotic solutions to this question, but to be honest, I don't see the appeal.

Titoism answered 16/4 at 3:13 Comment(2)
As is the case with most shell "best practices" pages the referenced page contains some bad advice, including the recommendation to always use set -eo pipefail. See Bash Pitfalls #60 (set -euo pipefail). (The Greg's Wiki site is one of the few, and arguably the only, reliable source of good information about Bash programming.) Questions about problems (that turn out to be) caused by set -e and/or set -o pipefail are very common on this site.Akihito
thank you for the comment, I will probably remove that section of the answer :)Titoism

© 2022 - 2024 — McMap. All rights reserved.