Reputation: 185
I recently learned about an if statement that looks at previous command and if failed will send exit code 1 with a message. I can't remember the entire statement but it starts with the below:
if [ $? != "0" ]
How does this statement end? Does it follow every command within a script?
Upvotes: 0
Views: 492
Reputation: 212228
Don't do that. Explicitly referencing $?
is almost never necessary. If you want to exit with status 1 when a command fails, you can simply do:
cmd || exit 1
If you want to exit with the same non-zero value returned by the command, you can simply do:
cmd || exit
There are a lot of examples of bad code out there that instead do things like:
cmd
if [ "$?" -ne 0 ]; then echo cmd failed >&2; exit 1; fi
and this is bad practice for many reasons. There's no point in having the shell print a generic message about failure; the command itself ought to have written a detailed error message already, and the vague "cmd failed" is just line noise. Also, you will often see set -e
, which basically slaps a || exit
on the end of every simple command but has a lot of unintended side effects and edge cases, and its implementation has changed throughout history and different versions of the same shell will handle the edge cases differently so it's really not a good idea to use it.
As to the question "how does this statement end?"; it ends with fi
. The general form of if
is if CMD; then ...; else ...; fi
where CMD is some set of pipelines (eg, you can do if echo foo | grep bar; cmd2 | foo; then ....
). If the CMD returns a 0 status the first set of commands (between "then" and "else") is executed. If CMD returns non-zero, the commands between "else" and "fi" are executed. The "else" clause is optional. Don't be fooled by [
; it is simply a command. In my opinion, it would be clearer if you used its alternate spelling test
, which does not require a final argument of ]
. IOW, you could write if test "$?" -ne 0; then ...; fi
.
Upvotes: 1