(Not exactly equivalent because there won't be an "exit" if echo fails, but it's my preferred instict over ";") Also, "(" starts a subshell, if we are being pedantic.
I wonder if there’s some obscure syntax for "do this if the preceding command fails and propagate its exit code". For just returning some error you can of course have something like `die("boom")` (though not as a builtin?) but sometimes it’s useful to know the exact code.
test 1 == 2 && echo "ok" || (error_code="$?"; echo "failed with '$error_code'"; exit "$error_code")
When command (test 1 == 2) fails, it goes to the "or" section, sets the error_code variable, does something (echo command, but it could be anything), and then re-exits with the same exit code.
It's not so obscure, there is just no native "re-raise" function so you have to record the exit code yourself (actually, bash's built-in exit will return the last command's exit code, but in the example above, that's the "echo" which actually succeeds).
Edit: since the above runs it in a subshell, $error_code is not available outside the parentheses but if you need this, you can try:
test 1 == 2 && echo "ok" || error_code="$?" && echo "failed with '$error_code'"
exit $error_code
necovek · · focus · HN ↗
I'd even drop the "if" from their footnote version, and go with simply
(Not exactly equivalent because there won't be an "exit" if echo fails, but it's my preferred instict over ";") Also, "(" starts a subshell, if we are being pedantic.Sharlin · · focus · HN ↗
necovek · · focus · HN ↗
It's not so obscure, there is just no native "re-raise" function so you have to record the exit code yourself (actually, bash's built-in exit will return the last command's exit code, but in the example above, that's the "echo" which actually succeeds).
Edit: since the above runs it in a subshell, $error_code is not available outside the parentheses but if you need this, you can try: