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.