【发布时间】:2012-09-27 17:40:42
【问题描述】:
在了解bash 的同时,我看到了四种使用if 语句的方法:
- 单括号 - ( ... )
- 双括号 - (( ... ))
- 单方括号 - [ ... ]i>
- 双方括号 - [[ ... ]]
bash 中的括号和方括号有什么区别。
【问题讨论】:
标签: bash bash if-statement
在了解bash 的同时,我看到了四种使用if 语句的方法:
bash 中的括号和方括号有什么区别。
【问题讨论】:
标签: bash bash if-statement
您列出的测试:
test 的语法
test,但更强大)并不详尽,您可以使用布尔逻辑
if command; then ...
也是,因为命令具有退出状态。在bash 中,0 是 true 并且 > 0 是 false。
你可以看到这样的退出状态:
command
echo $?
见:
http://wiki.bash-hackers.org/syntax/basicgrammar
http://wiki.bash-hackers.org/syntax/arith_expr
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
【讨论】:
$? 不完全是返回值,实际上是退出状态; 0代表成功,1代表失败,可以解释为真假。
curl /dev/null exit with 3
exit -1 导致退出值为 255
shell 本身只运行命令并评估其退出代码。零退出代码表示成功;所有其他值都表示失败。
if command; then
: things to do if the exit code from command was 0
else
: things to do if it was not 0
fi
while command; do
: things to do if the exit code was 0
done
命令[(又名test)在条件句中非常常用,因为原始的 Bourne shell 缺少内置运算符来检查字符串是否为空或文件是否存在。现代 shell 内置了这个命令,许多 shell 有一个扩展和现代化的版本 [[,但这不能正确地移植到 POSIX sh,因此应该避免用于可移植脚本。 This related question 更详细地解释了两者之间的区别。
符号(( ... )) 引入了算术上下文。同样,这不是原始 Bourne shell 的一部分(它有一个专用的外部工具 expr 用于这些东西),但现代 shell 内置了它。如果算术表达式的结果代码为 0算术评估不为 0(或错误)。
符号( command ) 创建一个子shell 并在其中评估command。在某些情况下,这实际上是必要且有用的,但如果您只是学习语法,则不太可能需要它。
...事实上,在我看到的大多数脚本中,它都用在条件句中,这显然是不必要的。
另一个需要注意的反模式是
command
if [ $? = 0 ]; then
: things
fi
您几乎不需要明确地检查$?,特别是,将其与零进行比较是if 和while 专门在幕后为您做的事情。这应该简单地重构为
if command; then
: ...
【讨论】: