2

I'm writing a script and I'd like to use set -o pipefail on shells that support it. Dash does not support that option. Usually, || true lets me swallow errors, but not in case of set:

> podman run python:3.8 sh -c "set -o pipefail && echo OK || echo BAD"                         
sh: 1: set: Illegal option -o pipefail

The error terminates the script execution immediately without giving me a chance to catch it.

2
  • 1
    If you're writing for bash why bother trying to support dash? Keep it simple and either make bash a prerequisite or else drop back to writing POSIX shell code and avoid using bashisms. If you mix you'll either lose the benefit of one or have unexpected effects from code that's unsupported Commented 9 hours ago
  • 1
    Note that dash supports pipefail since version 0.5.13 Commented 8 hours ago

2 Answers 2

4

set is a special built-in, and per POSIX, errors in special built-ins shall cause an interactive shell to exit. But you can use command to "de-specialize" it. (this is straight up mentioned in the footnote under the table in 2.8.1 Consequences of Shell Errors)

So, command set -o pipefail seems to do what you want in most shells I tried. But zsh made an exception in that command set just didn't work in the default mode. (It did seem to work if executed in sh mode.)

1
  • 1
    zsh's command predates POSIX' command and behave differently. However, in sh emulation it should behave more POSIXly. Commented 8 hours ago
2

In the end I had to run a sub-shell just to check whether set -o pipefail will work.

# Workaround for Dash and other shells that do not support -o pipefail.
if (set -o pipefail 2>/dev/null); then
    set -o pipefail
fi
1
  • 1
    For the record, pipefail is now standard for sh since the 2024 edition of the POSIX standard, is initially from ksh and is now supported in dash since version 0.5.13 Commented 8 hours ago

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.