OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Escaping Characters

Sometimes we only want to quote a single character. To do this, we can precede a charac- ter with a backslash, which in this context is called the escape character. Often this is done inside double quotes to selectively prevent an expansion:



[me@linuxbox ~]$ echo "The balance for user $USER is: \$5.00"

The balance for user me is: $5.00

[me@linuxbox ~]$ echo "The balance for user $USER is: \$5.00"

The balance for user me is: $5.00


It is also common to use escaping to eliminate the special meaning of a character in a filename. For example, it is possible to use characters in filenames that normally have special meaning to the shell. These would include “$”, “!”, “&”, “ ”, and others. To in- clude a special character in a filename you can do this:



[me@linuxbox ~]$ mv bad\&filename good_filename

[me@linuxbox ~]$ mv bad\&filename good_filename


To allow a backslash character to appear, escape it by typing “\\”. Note that within single quotes, the backslash loses its special meaning and is treated as an ordinary character.


image

Backslash Escape Sequences

In addition to its role as the escape character, the backslash is also used as part of a notation to represent certain special characters called control codes. The first 32 characters in the ASCII coding scheme are used to transmit commands to tele- type-like devices. Some of these codes are familiar (tab, backspace, linefeed, and carriage return), while others are not (null, end-of-transmission, and acknowl- edge).


Escape Sequence

Meaning

\a

Bell (“Alert” - causes the computer to beep)

\b

Backspace

\n

Newline. On Unix-like systems, this produces a linefeed.

\r

Carriage return

\t

Tab


The table above lists some of the common backslash escape sequences. The idea behind this representation using the backslash originated in the C programming language and has been adopted by many others, including the shell.

Adding the “-e” option to echo will enable interpretation of escape sequences. You may also place them inside $' '. Here, using the sleep command, a sim- ple program that just waits for the specified number of seconds and then exits, we can create a primitive countdown timer:

sleep 10; echo -e "Time's up\a"

We could also do this:

sleep 10; echo "Time's up" $'\a'


Top OS Cloud Computing at OnWorks: