3 ms·
I was pretty close in guessing what they believe was "wrong" (or really, superfluous) with their initial shell script example. I'd even drop the "if" from thei
by necovek 6d ago
I was pretty close in guessing what they believe was "wrong" (or really, superfluous) with their initial shell script example.
I'd even drop the "if" from their footnote version, and go with simply
npm install || (echo "boom" && exit)
(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 6d agoI 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.
- deleted 6d ago[deleted]
- dasyatidprime 6d agoif table --warble farble; then :; else table_ec=$?; echo "Garble warble farble! :(" >&2; exit $table_ec; fi Works in dash/bash/zsh at least; not 100% sure whether the behavior of $? on the command in an if test is mandated by POSIX and/or portable. Note that you can't replace the empty then-branch with a negated condition because the negation also eats the return code. Also, absolutely correct propagation is essentially impossible (but usually not useful anyway), because some errors might be unexpected signal exits or inability to find the command in the first place, and those will get punned onto other nonzero exit codes. I forget the exact conventions OTTOMH but generally they're in the high half (≥128).
- necovek 6d agoSignals get a 128+n, with n being the signal code. Where texinfo is available, "info bash" is a great reference; "man bash" is everything in a single page — so less manageable — but you can look for BUILTIN section, which documents "exit" built-in function (among other things).
- necovek 6d agotest 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