字符串 – “[]”与“[[]]”在Bash shell中

前端之家收集整理的这篇文章主要介绍了字符串 – “[]”与“[[]]”在Bash shell中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?7个
这可能已经回答了,但无论如何我都会问它.我有两个版本的脚本(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!

#!/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

有人可以解释我为什么不同?

另外 – 在什么情况下应该使用[]而不是[[]],反之亦然?

test的字符串相等运算符不执行globs.
$[ abc = *bc ] ; echo $?
1
$[[ abc = *bc ]] ; echo $?
0

猜你在找的Bash相关文章