是[[]] preferable超过[]在bash脚本? [英] Is [[ ]] preferable over [ ] in bash scripts?

查看:91
本文介绍了是[[]] preferable超过[]在bash脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个同事在code审查,在[[]]结构就是要preferred在[]中构造,如

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的不指定它做什么,只有一些炮弹支持它(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).

[也有其他一些不错的功能,像 =〜常规EX pression匹配沿与运营商,就像他们在类似C语言中是已知的。这里是一个关于它的良好页:是什么测试之间的区别, [ [猛砸测试

[[ 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

这篇关于是[[]] preferable超过[]在bash脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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