I'm used to this style in other languages:
do_something || (log_error; return 1) # do something, and if that fails, log the error and then return 1 no matter what, even if the logging fails.
But I can't seem to find an equivalent in bash. The problem is that the parenthesis work kind of like a function with its own scope, and the return 1 won't have the expected behavior.
This is what I have so far, but it's not perfect:
! do_something && log_error && return 1
The problem with this is that the ! is confusing, and the return 1 depends on the success of the logging.
This one is better, but more verbose:
do_something || (log_error; return 1) || return 1
Any thoughts?
return
statement is meaningful only when inside a script or function - not on the command line. Who do you want to return 1 to?return
to return from a shell function but continue executing the script from where it was called; useexit
to exit the entire shell (i.e. the script). Unless you're in parentheses, in which case you're in a subshell andexit
only exits the parenthesized (subshell) expression.exec >output.log 2>error.log
and it won't mess up the calling script. Or you can use{ payload; } >output.log 2>error.log
and the redirect will only apply to what's in the brackets, without needing a subshell.