"[]" versus "[[]]" in the Bash shell

This can be answered, but I’ll ask anyway. I have two versions of 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

Can someone explain to me why the difference?

Also - under what circumstances should be used [ ]against [[ ]]and vice versa?

+5
source share
3 answers

test The string equality operator does not execute globes.

$ [ abc = *bc ] ; echo $?
1
$ [[ abc = *bc ]] ; echo $?
0
+4
source

[[is a built-in bash and cannot be used in a #!/bin/shscript. You need to read the Conditional Commands section in the bash manual to find out the possibilities [[. The main advantages of spring:

  • == != ,
  • =~ !~ . BASH_REMATCH.
  • && ||
  • , .

: script bash -.

+12

Also - under what circumstances should [ ] be used vs. [[ ]] and vice versa?

. , , [[. , [[ , [[, . [[, .

+2

All Articles