Originally Posted by hapihakr
...why is it 'case "$1" in' rather than 'case $1 in'?
Again, the quotes prevent unintended consequences, when expanding the variable. Imagine if a user called the command with:
Then 'case "$1" in' would become 'case |reboot in' and your machine would reboot.
You're certainly right about unintended consequences as a general principle, but you aren't quite correct in this specific situation.
In general, once a character is inside a variable it loses it's special meaning. It's only when the string is re-expanded, and again interpreted by the shell
, that it becomes special again. How it's interpreted depends on the context it's used in, however, and some shell built-ins in particular have their own processing rules.
In the case of the case
keyword, the contents of the variable aren't interpreted as commands, so any shell-reserved characters such as pipes inside them remain safe. Even whitespace is ok, since word-breaking doesn't occur either. case
only views the contents as a literal string to match against.
So case $1 in
and case "$1" in
are exactly the same syntax-wise. The quotes don't help, but they don't hurt either. When in doubt, always quote.
Understanding how quotes work is vital, and I applaud the OP for taking the time to study it. If he hasn't seen these links before, I recommend them now (in addition to the "quotes" link given above):
BTW, the [[..]]
test keyword is another place where quoting isn't necessary, at least for the left side of the equation. They can be important on the right side if you're doing globbing or regex matches.