我偶然发现了这段代码,并问了自己它的重要性:
mdl.add(nbKindOfBuses==(nbbus40>=1)+(nbbus30>=1))
让我烦恼的是[$? = 4]部分。看起来好像对最后一个命令的退出代码进行了测试,因为“#做某事”和“#做另一件事”与如何处理不同版本的getopt有关,所以这很有道理,但是它甚至得到了评估吗?如果是这样,怎么办?在if关键字之后,我从未见过这样的声明。
谢谢!
答案 0 :(得分:2)
让我们回顾一下help if
的输出:
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi The `if COMMANDS' list is executed. If its exit status is zero, then the `then COMMANDS' list is executed. Otherwise, each `elif COMMANDS' list is executed in turn, and if its exit status is zero, the corresponding `then COMMANDS' list is executed and the if command completes. Otherwise, the `else COMMANDS' list is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true.
鉴于上述情况,请考虑以下事项:
if COMMANDS; then ...
特别接受COMMANDS
-一个列表,该列表可以包含由分隔符组合的多个命令。foo; bar
是同时运行foo
和bar
的命令列表;完成后,复合命令的退出状态为bar
。[ $? = 4 ]
测试前一个程序的退出状态是否正好是4。getopt -T >/dev/null 2>&1; [ $? = 4 ]
因此测试getopt -T
是否以精确为4的状态退出。因此,如果#do a thing
失败并退出状态为4,则代码运行getopt -T
块,否则运行#do the other thing
。