Using Shell Quoting
Problem
You need a rule of thumb for using command-line quoting.
Solution
Enclose a string in single quotes unless it contains elements that you want the shell to interpolate.
Discussion
Unquoted text and even text enclosed in double quotes is subject to shell expansion and substitution. Consider:
$ echo A coffee is $5?! A coffee is ?! $ echo "A coffee is $5?!" -bash: !": event not found $ echo 'A coffee is $5?!' A coffee is $5?!
In the first example, $5 is
treated as a variable to expand, but since it doesn’t exist it is set to
null. In the second example, the same is true, but we never even get
there because !” is treated as a history substitution, which fails in
this case because it doesn’t match anything in the history. The third
example works as expected.
To mix some shell expansions with some literal strings you may use the shell escape character \ or change your quoting. The exclamation point is a special case because the preceding backslash escape character is not removed. You can work around that by using single quotes or a trailing space as shown here.
$ echo 'A coffee is $5 for' "$USER" '?!' A coffee is $5 for jp ?! $ echo "A coffee is \$5 for $USER?\!" A coffee is $5 for jp?\! $ echo "A coffee is \$5 for $USER?! " A coffee is $5 for jp?!
Also, you can’t embed a single quote inside single quotes, even if using a backslash, since nothing (not even the backslash) is interpolated inside single quotes. But you can work around that by using double quotes with escapes, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access