为什么要引用$?明确地
很多 sh 代码看起来像:
$cmd if [ $? = 0 ]; then $cmd2; fi
而不是:
if $cmd; then $cmd2; fi
我通常假设人们使用前者只是因为他们不知道后者的语法是有效的,但我想知道是否还有其他原因(尽管唯一的可能性是我想到的是便携性)。是否有任何理由更喜欢显式引用 ${?}?。
A lot of sh code looks like:
$cmd if [ $? = 0 ]; then $cmd2; fi
Instead of:
if $cmd; then $cmd2; fi
I have typically assumed that people use the former simply because they are unaware that the syntax of the latter is valid, but I'm wondering if there is another reason (although the only possibility that comes to mind is portability). Is there any reason to prefer explicitly referencing ${?}?.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您确实想将错误代码用于某些用途(日志记录、处理预期错误等),则必须引用
$?
。对于您提到的特定场景,第二个if
构造更清晰、更短,我认为没有理由不使用它。You have to reference
$?
if you actually want to use the error code for something (logging, handling expected errors, etc.). For the particular scenario that you mention, the secondif
construct is both clearer and shorter, and I see no reason not to use it.在我看来,因为很多人没有意识到你可以或多或少地测试命令的状态。同样,人们也没有意识到你可以写:
你还可以将你的代码简化(以简洁为代价)为:(
我看到@shin在评论中指出了这一点,我已经投了赞成票)。
我还看到很多“Bourne”shell 代码使用:
有时这是合适的 - 但大多数情况下,它是 C shell 程序员编写的东西,没有意识到该符号在 Bourne shell 和衍生产品中意味着“运行子 shell” -例如 Korn shell、符合 POSIX 标准的 shell 和 Bash。
In my view, because a lot of people don't realize that you can test the status of the command more or less as you do. Similarly, people also do not realize that you can write:
You can also simplify your code (at the cost of terseness) to:
(I see @shin noted this in a comment, which I've up-voted).
I also see a lot of 'Bourne' shell code that uses:
Sometimes that is appropriate - but most often it is stuff that a C shell programmer wrote not realizing that the notation means 'run a sub-shell' in Bourne shell and derivatives - such as Korn shell, the POSIX-compliant shells, and Bash.
因为您正在测试命令的状态标志,而不是测试命令的输出。如果命令打印到 stdout,但设置了标志,您会得到不同的结果您给出的两个示例的结果。经过测试后,我已经纠正了。我想我记得几年前在Solaris上遇到了一个问题(在ksh下?),但除了测试之外,我无法在当前有权访问的机器下重新创建:
if [
$cmd
]Because you're testing the status flag of the command, as opposed to testing the output from the command.If a command prints to stdout, but sets a flag, you'll get get different results with the two examples you've given.I stand corrected, after testing it. I thought I remembered running into a problem years ago on solaris (under ksh?), but I can't recreate under the machines I currently have access to except for testing :
if [
$cmd
]是的,很多人不知道后者更优雅的形式。
我之前在以下文章中提到过这一点:
http://www.pixelbeat.org/programming/shell_script_mistakes.html
Yes many people don't know about the latter more elegant form.
I've previously mentioned this in:
http://www.pixelbeat.org/programming/shell_script_mistakes.html