13

How can I use set -e semantics in a function?

This is reopen to "set -e" in a function question since it has not been answered correctly and has already been accepted.

Here is example:

#!/bin/bash
set -exo pipefail
f() {
    echo a
    false
    echo Should NOT get HERE
}
if f ; then
    true
fi

I would like f to exit at false.

My experiments show that using subshell (f) call doesn't help here:

#!/bin/bash
set -exo pipefail
f() {
    echo a
    false
    echo Should NOT get HERE
}
g() {   
    ( f )
}
if g ; then
    true
fi

Moving f out of the if statement does the job of course in this particular case:

#!/bin/bash
set -exo pipefail
f() {
    echo a
    false
    echo Should NOT get HERE
}
f
if [ "$?" != "0" ] ; then
    true
fi

This doesn't help me that much tough.

Is it possible to turn on set -e semantics when the function is executed from within the if predicate?

Community
  • 1
  • 1
agsamek
  • 8,734
  • 11
  • 36
  • 43
  • 1
    I marked this as a duplicate because asking a duplicate question isn't really a solution to being unhappy with an answer. It just fragments the answers, when we already have a mechanism to provide multiple answers. Can we clean this up back into a single question? I would be happy to unaccept and switch to the best answer again. – Robie Basak Aug 02 '13 at 00:15

0 Answers0