While the man page is not incorrect, I agree that this behavior is not exactly obvious - you have to infer it. With -e (but without -E): The ls command fails inside your function, and because set -e is in effect, Bash instantly exits, directly from the function scope - and since there is no ERR trap in effect there (because it wasn't inherited from the parent scope), your trap is not called. In that scope, the ERR trap is in effect, and it is invoked (but note that execution will continue, unless you explicitly call exit from the trap). Without -e: The ls command fails inside your function, and, due to being the last command in the function, the function reports ls's nonzero exit code to the caller, your top-level script scope. The ERR trap is normally not inherited in such cases. If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. Man bash says about set -o errtrace / set -E: The argument that is checked for an error. Syntax IFERROR (value, valueiferror) The IFERROR function syntax has the following arguments: value Required. IFERROR returns a value you specify if a formula evaluates to an error otherwise, it returns the result of the formula. # even though the failure occurs *inside the function*.Ī more sophisticated example trap example that prints the message in red and also prints the exit code: You can use the IFERROR function to trap and handle errors in a formula. # Thanks to -E / -o errtrace, this still triggers the trap, Set -eE # same as: `set -o errexit -o errtrace` In short: use set -eE in lieu of just set -e: #!/bin/bash Chepner's answer is the best solution: If you want to combine set -e (same as: set -o errexit) with an ERR trap, also use set -o errtrace (same as: set -E).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |