7.2.8. Quote removal

After the expansions, the final step before executing the command is the removal of the quotes. Quotes are used to ‘protect’ some special characters from interpretation by the shell. There are three kinds:

” (double quote)

everything is taken litteraly except

$ (variable substitution)

` (command substitution)

(escaping)

” (ends the double quotes)

‘ (single quote)

everything is taken litteraly except

‘ (ends the single quotes)

(backslash)

the character after the is taken litteraly.

This is called ‘escaping a character’.

Some examples:

% fruit=apple
% echo $fruit
apple
% echo "$fruit"
apple
% echo \"$fruit\"
"apple"
% echo '$fruit'
$fruit
% echo \$fruit
$fruit
% echo '\$fruit'
\$fruit
% echo \$$fruit
$apple

To search for a backslash character in a file, this character has to be escaped. But remember what is said here the is also a special character in regular expressions and also has to be escaped when used in a grep-pattern. This results in the following (remember, echo shows how the shell ‘sees’ the command):

% grep \\ *.t2t
grep: Trailing backslash    # gives an error, to see what happens we use echo
% echo grep \\ *.t2t
grep \ basic.t2t contents.t2t local.t2t playing.t2t shell.t2t start.t2t ...

--> grep sees only one \

% echo grep '\\' *.t2t
grep \\ basic.t2t contents.t2t local.t2t playing.t2t shell.t2t start.t2t ...

--> the \\ are just interpreted as normal characters between the ' ', and are
    given to grep as such. grep interpretes the \\ as an escaped backslash
    and will search for a single backslash in the given files


% echo grep [\\] *.t2t
grep [\] basic.t2t contents.t2t local.t2t playing.t2t shell.t2t start.t2t ...

--> only one \ remains, but in a []-construct the \ looses its meaning for grep
   grep will search for a single backslash in the given files

Can you solve this using double quotes ?

Note about command substitution

Within command substitution we had two forms that are in use, the $(...) and the `...` constructions. The behave differently for quoting. In the older form, ` command `, the \ has no special meaning except when it is followed by $, ` or \ (another backslash). In the $(command) form, no character has a special meaning. In practice that means that for the latter, you can just write the command and put it between $( ) to save it into a variable. For the former, before putting it between ` `, you have to escape the \, $ and `.

For example, if you want to save the list of files that contains a litteral $, you can do the following (remember, the $ has to be escaped for grep, it means otherwise ‘end of line’, see grep:

# command we want to run : grep -l '\$' *.t2t

c=$(grep -l '\$' *.t2t)
c=`grep -l '\\$' *.t2t`  # the two \\ become \, so grep sees \$
c=`grep -l '\\\$' *.t2t` # the two \\ become \, the \$ becomes $, so grep sees \$

In practice, the $() expansion is easier to use and is the preferred form in a modern bash environment (see here).