[Next] [Previous] [Up] [Top] [Contents]

CHAPTER 9 Shell Programming

9.3 Quoting


We quote strings to control the way the shell interprets any parameters or variables within the string. We can use single (') and double (") quotes around strings. Double quotes define the string, but allow variable substitution. Single quotes define the string and prevent variable substitution. A backslash (\) before a character is said to escape it, meaning that the system should take the character literally, without assigning any special meaning to it. These quoting techniques can be used to separate a variable from a fixed string. As an example lets use the variable, var, that has been assigned the value bat, and the constant string, man. If I wanted to combine these to get the result "batman" I might try:

$varman

but this doesn't work, because the shell will be trying to evaluate a variable called varman, which doesn't exist. To get the desired result we need to separate it by quoting, or by isolating the variable with curly braces ({}), as in:

"$var"man - quote the variable

$var""man - separate the parameters

$var"man" - quote the constant

$var''man - separate the parameters

$var'man' - quote the constant

$var\man - separate the parameters

${var}man - isolate the variable

These all work because ", ', \, {, and } are not valid characters in a variable name.

We could not use either of

'$var'man

\$varman

because it would prevent the variable substitution from taking place.

When using the curly braces they should surround the variable only, and not include the $, otherwise, they will be included as part of the resulting string, e.g.:

% echo {$var}man

{bat}man


Introduction to Unix - 14 AUG 1996
[Next] [Previous] [Up] [Top] [Contents]