Jordan
Jordan

Reputation: 4502

Conditionally setting "-o pipefail" in /bin/sh

I have a script that uses the #!/bin/sh shebang to be compatible with many flavors. If this results in a shell that supports it being used, I'd like to run set -o pipefail.

How can I either (a) check if the shell supports pipefail, or (b) try to set pipefail and "catch"/suppress the error if that command fails?

Upvotes: 3

Views: 3093

Answers (2)

Kninnug
Kninnug

Reputation: 8053

Mark's answer did not work for me with Dash-0.5.10.2-6. The script exits as soon as the set -o pipefail line fails, despite it being 'negated' by !.

I managed to make it work by running set -o pipefail in a sub-shell:

#!/bin/sh

if ! (set -o  pipefail 2>/dev/null); then
    echo "There is no pipefail"
else
    echo "Setting pipefail"
    set -o pipefail
fi

false | true
echo "false | true -> $?"

Note that this doesn't actually set -o pipefail in the current script if it succeeds, which is why it is executed again in the else branch.

Running it with Dash:

$ dash ./pipefail.sh 
There is no pipefail
false | true -> 0

Running it with Bash:

$ bash ./pipefail.sh 
Setting pipefail
false | true -> 1

Upvotes: 4

Mark
Mark

Reputation: 4455

Benjamin W.'s response was accurate - you can just suppress the error message with 2>/dev/null and check the error code:

#!/bin/sh

if 
  ! set -o pipefail 2> /dev/null   
then
  : take some action if there is no pipefail option
fi

Upvotes: 1

Related Questions