The previous section should clearly demonstrate that there are a number of characters that are special to the shell, and hence some extra measures must be taken when attempting to use them in a casual manner. For illustration of this point, imagine a directory containing the following files:
Mail/ News/ a.out* prog.c utils/
and the user types, while in this directory,
$ echo * Hello *
Expecting the following output:
* Hello *
The user is shocked to see the actual output:
Mail News a.out prog.c utils Hello Mail News a.out prog.c utils
The shell has simply used its definition of the * symbol
which differs greatly from the users definition of the same character.
This is a common example of how care has to be taken when using shell
special characters in strings.
There are a few ways to handle this situation.
The first solution, which is probably the easiest for this particular
example, is to escape the *.
This means that a backslash should be placed directly in front of the
*.
Escaping a character causes it to be treated by the shell as though it
were simply a text character.
Therefore the above example could be quickly corrected by entering the
following:
$ echo \* Hello \*
which would give the desired result.
The result could also be achieved using single (left hand) or double
quotation marks.
When either single or double quotation marks enclose a string, the
special characters (with the exception of the $ and right hand
single quote (')) are taken to be string characters.
An advantage of quotation marks over escape sequences is that if there
are many special characters in a string, quotes will save keystrokes
and thus time.
Another advantage is that they recognize white space.
An echo statement without quotation marks will not recognize
spaces or tabs causing the following:
$ echo \*\*Warning\*\* Disk Space is Low
which will give as output:
**Warning** Disk Space is Low
A quick and easy fix would be
$ echo '**Warning** Disk Space is Low'
and this would give the appropriate output. While both single and double quotes solve the above problems, they are different. The difference comes in handling variables, which will be covered shortly. The single quote will not substitute a variable into an expression whereas the double quote will. When deciding which of the methods to use, the complexity of the expression (i.e. how many special characters are used) should be looked at, as well as variable usage.
Command substitution is a topic that ties up these last few sections. Command substitution allows the output of a command to be substituted into another command. For example,
$ echo "There are `who | wc -l` users on the system"
may give as output
There are 13 users on the system
The user now has the tools and flexibility to handle even the most specific or complicated command in the Bourne shell.