"[ ]" vs. "[[ ]]" in Bash shell
This may be answered already but I am going to ask it anyways. I have two versions of a script ( 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?
test
的字符串相等运算符不会做任何事情。
$ [ abc = *bc ] ; echo $?
1
$ [[ abc = *bc ]] ; echo $?
0
[[
is a bash built-in, and cannot be used in a #!/bin/sh
script. You'll want to read the Conditional Commands section of the bash manual to learn the capabilities of [[
. The major benefits that spring to mind:
==
and !=
perform pattern matching, so the right-hand side can be a glob pattern =~
and !~
perform regular expression matching. Captured groups are stored in the BASH_REMATCH
array. &&
and ||
The major drawback: your script is now bash-specific.
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.
上一篇: Bash脚本:在脚本中查找最小值