Discussion:
[Help-bash] equivalent of set -e for function
Peng Yu
2018-12-04 15:57:49 UTC
Permalink
Hi,

I'd like to return from a function upon getting an error from a
command in that function. It seems that `set` does have an option like
-r for this feature. Does bash support this feature via some other
setup command? Thanks.
--
Regards,
Peng
Daniel Mills
2018-12-04 16:18:46 UTC
Permalink
Post by Peng Yu
Hi,
I'd like to return from a function upon getting an error from a
command in that function. It seems that `set` does have an option like
-r for this feature. Does bash support this feature via some other
setup command? Thanks.
--
Regards,
Peng
:Just use some_command || return, though I guess you could do it with an
ERR trap. trap return ERR
Peng Yu
2018-12-05 05:22:01 UTC
Permalink
:Just use some_command || return, though I guess you could do it with an ERR trap. trap return ERR
I'd like to automatically check for errors. So some_command || return
is not an option as it will require the insertion of many trailing
returns.

I'd like to return from the function in trap ERR. But it seems that
the code trapped to ERR is considered to be outside of the function,
therefore can not be returned from the function. Is there any other
walkaround?

$ cat main.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -E
trap 'declare -p BASH_COMMAND; { ( return ) } 2>/dev/null; echo "$?"' ERR
function f {
false
declare -p FUNCNAME
}
f

$ ./main.sh
declare -- BASH_COMMAND="false"
1
declare -a FUNCNAME=([0]="f" [1]="main")
--
Regards,
Peng
Loading...