-2

When shell programming we need to care for proper quoting, so parameter expansion does the right thing with respect to white space in expansions, or to prevent word splitting getting in the way. The canonical example is a file with a white space in the name:

DIR="My Documents"
cd $DIR              # Tries to "cd My".
cd "$DIR"            # Works.

Interestingly, quotes aren't needed in other places, since there is no word splitting performed:

SAVE_DIR=$DIR        # Assigns "My Documents", not just "My".
case $DIR in
   (My Documents)  printf 'My Documents\n';;   # This is output.
   (My)            printf 'My\n';;
esac

but this fails again:

test $DIR = "My Documents"   # Error: condition expected: My

Of course we can come up with a hard and fast rule like Always double quote your parameter expansions. But for the sake of getting smarter every day,

When are double quotes optional? So far I can see

  • in variable assignments (with a single expansion only)
  • as the word following a case token

Is this list complete? I'm sure it is not.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • I think this is a little open-ended for a question. But more objectively, it is shell-dependent; quotes are optional (to various degrees) inside `bash`'s `[[ ... ]]` expression, they are optional around (nearly?) all parameter expansions in `zsh`, etc. – chepner Apr 28 '13 at 16:20
  • Then let's assume we deal with the POSIX shell. Tag added. – Jens Apr 28 '13 at 20:08

1 Answers1

0

Other than what you have listed, I only came across the double brackets as chepner pointed out

$ set bird dog mouse

$ [[ $* = 'bird dog mouse' ]]; echo $?
0

Also quotes are optional with Herestrings

$ cat <<< $*
bird dog mouse

$ cat <<< "$*"
bird dog mouse

Except with a modified IFS

$ IFS=: cat <<< $*
bird dog mouse

$ IFS=: cat <<< "$*"
bird:dog:mouse
Community
  • 1
  • 1
Zombo
  • 1
  • 62
  • 391
  • 407