问题
I see this pattern in a lot of shell scripts, including instruction books, tutorials, and production scripts from large and well-established vendors.
command
if [ $? -eq 0 ]; then
things
fi
And yet I was told this is an antipattern. Why is that? What should I use instead?
回答1:
Shell scripts are often written by people who are not very familiar with the language. This makes for a lot of copy/paste code, even in scripts which would nominally have received a fair amount of review, scrutiny, and field testing.
The very purpose of the shell's flow control statements is to run a command and examine its exit code. In other words, if
already does exactly this. In this example, it runs [ $? -eq 0 ]
and examines whether the exit code from that is zero (indicating success) -- if so, it runs the then
branch, and otherwise the else
branch.
So, to reiterate, anything which looks like
command
if [ $? -eq 0 ]
is better expressed as just
if command
There are of course situations where you care about a specific non-zero exit code. Then you do have to examine and perhaps even copy the value of $?
(because it will be reset to the exit code of another command as soon as you run another external command). But examining whether or not it is zero is generally superfluous, and a demonstration of an incomplete understanding of the shell's syntax.
Similarly, while
runs a command and examines its exit code; if it is not zero, the loop is abandoned, and execution continues after the corresponding done
statement.
来源:https://stackoverflow.com/questions/56593969/why-is-if-eq-0-an-antipattern