Bash中单方括号和双方括号之间的区别 [英] Difference between single and double square brackets in Bash
问题描述
我正在阅读关于的bash示例,如果
但是一些示例是用单个方括号编写的:
I'm reading bash examples about if
but some examples are written with single square brackets:
if [ -f $param ]
then
#...
fi
其他双方括号:
if [[ $? -ne 0 ]]
then
start looking for errors in yourlog
fi
有什么区别?
推荐答案
单 []
是posix shell兼容条件测试。
Single []
are posix shell compliant condition tests.
Double [[]]
是标准<$ c $的扩展名c> [] 并受bash和其他shell支持(例如zsh,ksh)。它们支持额外的操作(以及标准的posix操作)。例如: ||
而不是 -o
和正则表达式匹配 =〜
。有关条件的 bash手册部分可以找到更完整的差异列表构造。
Double [[]]
are an extension to the standard []
and are supported by bash and other shells (e.g. zsh, ksh). They support extra operations (as well as the standard posix operations). For example: ||
instead of -o
and regex matching with =~
. A fuller list of differences can be found in the bash manual section on conditional constructs.
只要您希望脚本可以跨shell移植,请使用 []
。如果您希望 []
不支持条件表达式,请使用 [[]]
,并且不需要是可移植的。
Use []
whenever you want your script to be portable across shells. Use [[]]
if you want conditional expressions not supported by []
and don't need to be portable.
这篇关于Bash中单方括号和双方括号之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!