双方括号[[]]比Bash中的单方括号[]更好吗? [英] Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

查看:169
本文介绍了双方括号[[]]比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 ,因为它会拆分参数并扩展<$ c $之类的东西c>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 $ c> =〜以及类似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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆