Der Optimist
Der Optimist

Reputation: 21

Nested function in Bash: why does return stop parent function?

function test_ok {
  echo "function without error" || { echo "[Error] text"; return 1; }
  echo "this is executed"
}
function test_nok {
  echo "function with error"
  cause-an-error || { echo "[Error] text"; return 1; }
  echo "this is not executed"
  echo "this is not executed"
}
test_ok ; echo "$?"
test_nok ; echo "$?"

I would expect that the return 1 in function test_nok only exits the nested function { echo "[Error] text"; return 1; } and the following two echo commands are executed as they belong to the parent function test_nok.

But that's not true, echo "this is not executed" really is not executed and the exit code of test_nok is 1. This is the behavior I need, but I do not understand why it works that way => why is echo "this is not executed" not executed?

Upvotes: 1

Views: 316

Answers (2)

Der Optimist
Der Optimist

Reputation: 21

Gordon Davisson answered my question in a comment:

There's no nested function here. { } isn't a function, it just groups commands.

Upvotes: 1

builder-7000
builder-7000

Reputation: 7627

You could save the error code in a variable and return it at the end of the function (though this may not a good idea. i'd recommend to return when the error occurs) :

function test_nok {
    echo "function with error"
    cause-an-error || { error_code=$?; echo "[Error] text"; }
    echo "this is not executed"
    echo "this is not executed"
    return $error_code
}
test_nok
echo $?

Output:

function with error
./test.sh: line 5: cause-an-error: command not found
[Error] text
this is not executed
this is not executed
127

Upvotes: 0

Related Questions