Es posible que esto ya esté respondido, pero lo voy a preguntar de todos modos. Tengo dos versiones de un 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!

Y

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

¿Alguien podría explicarme por qué la diferencia?

Además, ¿en qué circunstancias debería [ ] ser utilizado vs. [[ ]] ¿y viceversa?

1

[[ 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
  • =~ performs regular expression matching. Captured groups are stored in the BASH_REMATCH array.
  • boolean operators && and ||
  • parenthèses for grouping of expressions.
  • no word splitting, so it’s not strictly necessary to quote your variables.

The major drawback: your script is now bash-specific.

1

test‘s string equality operator doesn’t do globs.

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

9

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

Eso depende. Si le preocupa la portabilidad y desea que sus scripts de shell se ejecuten en una variedad de shells, nunca debe usar [[. Si desea las funciones proporcionadas por [[ en algunas conchas, deberías usar [[ cuando desee esas funciones. Personalmente, nunca uso [[ porque la portabilidad es importante para mí.

6