Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash control flow using || on function, with set -e

If I put set -e in a Bash script, the script will exit on future errors. I'm confused about how this works with functions. Consider the following, which will only print one to standard out:

set -e # Exit on error
fun(){
    echo one
    non_existing_command
    echo two
}
fun

Clearly, the non_existing_command is an error and so the script exits before the second echo. Usually one can use the or operator || to run another command if and only if the first command fails. That is, I would suspect the following to print out both one and three, but not two:

set -e # Exit on error
fun(){
    echo one
    non_existing_command
    echo two
}
fun || echo three

What I get however is one and two. That is, the || operator prevents the exit (as it should) but it chooses to continue with the function body and disregard the right-hand command.

Any explanation?

like image 886
jmd_dk Avatar asked Aug 09 '17 21:08

jmd_dk


1 Answers

It appears to be documented in the set builtin command

If a compound command or shell function executes in a context where -e is being ignored [such as on the left-hand of a ||], none of the commands executed within the compound command or function body will be affected by the -e setting, even if -e is set and a command returns a failure status.

Emphasis and comment are mine.

Also, if you try to set -e within the function, don't bother: the next sentence:

If a compound command or shell function sets -e while executing in a context where -e is ignored, that setting will not have any effect until the compound command or the command containing the function call completes.

like image 125
glenn jackman Avatar answered Nov 18 '22 07:11

glenn jackman