在 Bash 中,双方括号 [[]] 比单方括号 [] 更可取吗? [英] Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?
问题描述
一位同事最近在一次代码审查中声称,在像
A co-worker claimed recently in a code review that the [[ ]]
construct is to be preferred over [ ]
in constructs like
if [ "`id -nu`" = "$someuser" ] ; then
echo "I love you madly, $someuser"
fi
他无法提供理由.有吗?
He couldn't provide a rationale. Is there one?
推荐答案
[[
有更少的惊喜,使用起来通常更安全.但它不是可移植的——POSIX 没有指定它的作用,只有一些 shell 支持它(除了 bash,我听说 ksh 也支持它).例如,你可以做
[[
has fewer surprises and is generally safer to use. But it is not portable - POSIX doesn't specify what it does and only some shells support it (beside bash, I heard ksh supports it too). For example, you can do
[[ -e $b ]]
测试文件是否存在.但是对于 [
,您必须引用 $b
,因为它拆分了参数并扩展了诸如 "a*"
(其中 [[
从字面上理解).这也与 [
如何成为外部程序并像其他程序一样正常接收其参数有关(尽管它也可以是内置程序,但它仍然没有这种特殊处理).
to test whether a file exists. But with [
, you have to quote $b
, because it splits the argument and expands things like "a*"
(where [[
takes it literally). That has also to do with how [
can be an external program and receives its argument just normally like every other program (although it can also be a builtin, but then it still has not this special handling).
[[
也有一些其他不错的特性,比如与 =~
匹配的正则表达式以及类似 C 语言的运算符.这是一个很好的页面:测试之间有什么区别,[
和 <代码>[[ ? 和 Bash 测试
[[
also has some other nice features, like regular expression matching with =~
along with operators like they are known in C-like languages. Here is a good page about it: What is the difference between test, [
and [[
? and Bash Tests
这篇关于在 Bash 中,双方括号 [[]] 比单方括号 [] 更可取吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!