Quoting Reserved Characters Part 1

Some characters are reserved within the context of the shell in that they have their own special meaning. The dollar ($), single quote (), double quote (), exclamation point (!), backslash (\) and the newline (<Enter>) which sends the command line to the shell for execution. Before one can pass any of these characters as an argument to a command you must quote it.

There are a number of ways one can quote characters. All have their merits in various situations thus a skilled operator should know the differences between them. Sometimes the various methods are combined in the same argument.

Subsequently my demonstration of quotation on the command line will be broken up into a series of blog posts. In the course of this series on quotation I will use echo which displays any text given to it as an argument thus it’s name.

Precede a reserved character with a backslash (\) to quote it. Backslash (\) is an escape character. Characters that immediately follow a \ will be taken as literals without special meaning. The one exception is the newline character.

echo the string “Isn’t this nice?“…
af@gaga:~$ echo Isn\’t this nice? <Enter>
Isn’t this nice?
af@gaga:~$

echo the string ““It isn’t nice!”“…
af@gaga:~$ echo \”It isn\’t nice\!\” <Enter>
“It isn’t nice!”
af@gaga:~$

echo the string “$HOSTNAME is nice!“…
af@gaga:~$ echo \$HOSTNAME is nice\! <Enter> (all on one line)
$HOSTNAME is nice!
af@gaga:~$

echo the string ““$HOSTNAME” is nice!” where $HOSTNAME is a shell variable to be expanded type…
af@gaga:~$ echo \”$HOSTNAME\” is nice\!
“gaga” is nice!
af@gaga:~$

The last two examples use the Bash variable HOSTNAME whose value is always the name of the current host. First the text “$HOSTNAME” is displayed because “$” is escaped and then in the last one the $HOSTNAME variable is expanded to the value of its contents. In this example the system’s name is gaga.

When passing a phrase to a command that takes multiple arguments one must also escape spaces. Thus the phrase in the first example becomes “Isn’\t\ this\ nice?

For escaping only one reserved character at a time the backslash is the easiest way but it becomes arduous when multiple escapes are required.

This entry was posted in BSD, Bash, GNU/Linux, UNIX and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>