1

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 ${?}?.

4

4 回答 4

5

$?如果您真的想将错误代码用于某些事情(日志记录、处理预期错误等),则必须参考。对于您提到的特定场景,第二个if结构更清晰、更短,我认为没有理由不使用它。

于 2009-12-22T17:07:59.053 回答
2

在我看来,因为很多人没有意识到你可以或多或少地像你一样测试命令的状态。同样,人们也没有意识到你可以这样写:

if cmd1
   cmd2
   cmd3
then
    ...do this after executing cmd1, cmd2 and cmd3, but ...
    ...only if cmd3 exits with with status 0!
fi

您还可以将代码(以简洁为代价)简化为:

cmd1 && cmd2

(我看到@shin 在评论中指出了这一点,我对此表示赞成)。

我还看到很多“Bourne”外壳代码使用:

if ( ... )
then ...
fi

有时这是合适的——但大多数情况下,这是 C shell 程序员编写的东西,没有意识到在 Bourne shell 和衍生工具(例如 Korn shell、POSIX 兼容的 shell 和 Bash)中该符号意味着“运行子 shell”。

于 2009-12-22T20:40:29.763 回答
1

是的,很多人不知道后者更优雅的形式。我之前在: http ://www.pixelbeat.org/programming/shell_script_mistakes.html 中提到过这一点

于 2009-12-23T11:00:22.920 回答
1

因为您正在测试命令的状态标志,而不是测试命令的输出。

如果一个命令打印到标准输出,但设置了一个标志,那么您将在给出的两个示例中得到不同的结果。

经过测试,我得到了纠正。我想我记得几年前在 solaris 上遇到过问题(在 ksh 下?),但除了测试之外,我无法在我目前可以访问的机器下重新创建:

如果 [ $cmd]

于 2009-12-22T17:07:40.007 回答