Bash shell 中的“[ ]”与“[[ ]]”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12063692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"[ ]" vs. "[[ ]]" in Bash shell
提问by AnBisw
This may be answered already but I am going to ask it anyways. I have two versions of a script (comp.sh)-
这可能已经回答了,但我还是要问一下。我有两个版本的脚本 ( comp.sh)-
#!/bin/sh
export tDay=$(date '+%Y%m%d')
newfile="filename_$tDay"
filename="filename_20120821100002.csv"
echo $newfile $filename
if [ $filename = *$newfile* ]
then
echo "Matched"
else
echo "Not Matched!"
fi
Output:
$ ./comp.sh
filename_20120821 filename_20120821100002.csv
Not Matched!
And
和
#!/bin/sh
export tDay=$(date '+%Y%m%d')
newfile="filename_$tDay"
filename="filename_20120821100002.csv"
echo $newfile $filename
if [[ $filename = *$newfile* ]]
then
echo "Matched"
else
echo "Not Matched!"
fi
$ comp.sh
filename_20120821 filename_20120821100002.csv
Matched
Could someone explain me Why the difference?
有人能解释一下为什么有区别吗?
Also - under what circumstances should [ ]be used vs. [[ ]]and vice versa?
另外 - 在什么情况下应该[ ]使用 vs.[[ ]]反之亦然?
采纳答案by Ignacio Vazquez-Abrams
test's string equality operator doesn't do globs.
test的字符串相等运算符不执行 globs。
$ [ abc = *bc ] ; echo $?
1
$ [[ abc = *bc ]] ; echo $?
0
回答by glenn Hymanman
[[is a bash built-in, and cannot be used in a #!/bin/shscript. You'll want to read the Conditional Commandssection of the bash manual to learn the capabilities of [[. The major benefits that spring to mind:
[[是 bash 内置的,不能在#!/bin/sh脚本中使用。您需要阅读bash 手册的条件命令部分以了解[[. 想到的主要好处:
==and!=perform pattern matching, so the right-hand side can be a glob pattern=~performs regular expression matching. Captured groups are stored in theBASH_REMATCHarray.- boolean operators
&&and|| - parenthèses for grouping of expressions.
- no word splitting, so it's not strictly necessary to quote your variables.
==并!=执行模式匹配,所以右手边可以是一个glob模式=~执行正则表达式匹配。捕获的组存储在BASH_REMATCH数组中。- 布尔运算符
&&和|| - 用于表达式分组的括号。
- 没有分词,所以引用你的变量不是绝对必要的。
The major drawback: your script is now bash-specific.
主要缺点:您的脚本现在是特定于 bash 的。
回答by William Pursell
Also - under what circumstances should [ ] be used vs. [[ ]] and vice versa?
Also - under what circumstances should [ ] be used vs. [[ ]] and vice versa?
It depends. If you care about portability and want your shell scripts to run on a variety of shells, then you should never use [[. If you want the features provided by [[on some shells, you should use [[when you want those features. Personally, I never use [[because portability is important to me.
这取决于。如果您关心可移植性并希望您的 shell 脚本在各种 shell 上运行,那么您永远不应该使用[[. 如果您需要[[某些 shell提供的功能,则应[[在需要这些功能时使用。就个人而言,我从不使用,[[因为便携性对我来说很重要。

