Should I use quotes to echo multiple words in bash?

Viewed 146

In shell scripts I usually use echo to print a message. When the message contains multiple words I have to options of how to do that:

# No quotes
echo Hello SO

or

# Quotes
echo 'Hello SO'

Is one way better than the other?

I know that quotes are very important when there are variables, special character, etc. So, this is another question.

1 Answers

Echo varies a lot accross implementations, but POSIX does mandate this:

STDOUT
The echo utility arguments shall be separated by single <space> characters and a <newline> character shall follow the last argument.

So if you don't quote, the shell will do its job and split the arguments on the whitespaces and then Echo will output each argument separated from the other by a single space:

$ echo Y X Z
Y X Z
$ echo Y   X   Z
Y X Z
$ echo 'Y   X   Z'
Y   X   Z

And of course, the whole line can still contain special tokens and fail altogether:

# Variable expansion
$ echo I have $2
I have
# Filename expansion
$ echo hi * there
hi Documents Downloads Music Pictures Videos there
# And other special tokens
$ echo hello (I am I)
bash: syntax error near unexpected token `('

When in doubt, quote it. For your particular example, no, it makes no difference.

Related