Bash glitch fast features

There are recommendations for using the following options to make Bash unsuccessful:

set -o errexit
set -o nounset
set -o pipefail

However, these options do not work as expected for the Bash functions passed through ||.

eg. in script

#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail

my_function() {
    test -z "$1"
    echo "this SHOULD NOT be printed"
}

my_function 1 || echo "???" # 1

my_function 1 # 2

echo "this will not be printed"

The line # 2will end the script with code 1 without output. This is what I expect.

The line # 1confuses me: it my_functionwill be completed successfully, printing "it SHOULD NOT be printed" and returning code 0, thus, "???" will not be printed.

How can I make Bash to process my_functionin line # 1in the same fast way as on line # 2?

+4
source share
2 answers

set -e/errexit:

, , ( if [ -d /foo ]; then) . [...] , ", if, " " , , ".

, . , Bash , Bash POSIX "". SubShell, - , Bash POSIX.

script , foo || bar , bar ( script). , && || script. , .

set -e, . , , .

+6

bash, trap:

trap [-lp] [arg] [sigspec …]

sigspec ERR, arg , ( ), , : . ERR , while while, if elif, , && ||, , final && ||, , , ​​ !. , errexit (-e).

. !

+2

Source: https://habr.com/ru/post/1665051/


All Articles