Quoting serves a couple of related purposes.
First, it's used to determine the initial line "tokens" (a.k.a. "words"). The first thing the shell does when it parses the line is break it up into individual command arguments. The first one becomes the command name, and all others are options, filenames, etc. Quotes and backslash escapes tell it that certain spaces aren't to be treated as token delimiters, allowing strings with whitespace in them to be grouped as single elements.
The second purpose is to protect shell-reserved characters in subsequent parsing steps. Anything that the shell would normally treat as special is ignored if it was initially escaped (and non-special characters don't change). This is where the difference between single and double quotes becomes important. A single quote will escape everything following it, up to the next single quote, but double-quotes allow a few characters to retain their special meanings, particularly "$
". This allows parameter expansions and substitutions to continue to occur, while still protecting everything else.
They also prevent these substitutions from being subsequently word-split and glob expanded. Yes, unquoted tokens can be sub-divided into more tokens in these steps, but the output of any parameter that was originally quoted will remain as a single token.
It's often useful to think of quotemarks as toggle switches, rather than containers. The first instance on the line turns off shell parsing, and the next one turns it on again, in a linear fashion. (Exceptions occur in certain nested constructs such as command substitutions, which are treated as separate quoting environments.)
If you see someone using an unquoted expression in a grep
command, say, then it's likely because he knows that the string contains nothing that needs to be protected. Simple one-word searches are usually safe, for example. But most regex and globbing characters are treated specially by both the shell and many other programs, so you need to be careful to pass them to the correct one.
This page lists pretty much everything that might need to be escaped.
In any case, it doesn't hurt to quote, even when unnecessary. So if in doubt, quote it!