3 ms·
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" secti
by necovek 12d ago
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