Why is if [ $? -eq 0 ] an antipattern? [duplicate]

蹲街弑〆低调 提交于 2020-01-05 07:00:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!