Reputation: 22043
I came across a small script:
$ for i in *.sh; do echo "$i"; done
name with space.sh
name_with_dash.sh
When I unquoted $i
, it produces the same result.
$ for i in *.sh; do echo $i; done
name with space.sh
name_with_dash.sh
I can see how "$i"
might need to be quoted for old-fashioned commands like test [ ]
, cd
, or rm
. Is it necessary to use quotes with echo
, too?
Upvotes: 1
Views: 82
Reputation: 780724
You'll see a difference if a filename contains multiple consecutive spaces:
touch "name with multiple spaces.sh"
With the quotes it will correctly echo:
name with multiple spaces.sh
Without the quotes it will combine all the spaces, displaying an incorrect filename:
name with multiple spaces.sh
The quotes prevent word-splitting, which parses the result of the variable expansion as words separated by whitespace (you can change the delimiter characters by setting the IFS
variable).
You'll rarely go wrong if you always quote your variables. You should only use the variable unquoted when you specifically need word splitting or wildcard expansions.
Upvotes: 5