1
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?

3
  • 2
    There's no nested function here. { }isn't a function, it just groups commands. Commented Jan 22, 2019 at 7:19
  • Thank you Gordon Davisson, that answers my question. But I think I cannot mark a comment as the solution, right? Commented Jan 22, 2019 at 7:31
  • 1
    If you only want to return from the "nested function" then use a subshell (...) instead of a group {...}. Commented Jan 22, 2019 at 7:38

2 Answers 2

1

Gordon Davisson answered my question in a comment:

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

Sign up to request clarification or add additional context in comments.

1 Comment

That was my intention, but I get the message "You can accept your own answer in 2 days". So I will accept it in 2 days or Gordon Davisson could write an answer that I can accept
0

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

3 Comments

Thank you. My posted code works like I need it, I just didn't understand why. But I think Gordon Davisson just answered my question => {} is not a function
Good, and regarding your question why is echo "this is not executed" not executed? you may want to read more about the { ...; } command in bash documentation: section of group command
Thank you Sergio, that's just what I did the last few minutes :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.