Removing Special Meanings in Command Lines


As you have seen throughout this chapter, the shell command language uses a number of special symbols. These include the I/O redirection operators >, <, and |, the wildcard characters * and ?, and the $ symbol for variables substitution. When you type in a command line containing one of these special shell characters, it is interpreted by the shell as an instruction. Sometimes, however, you need to use one of these symbols as a normal character. A simple example is using grep to search for lines containing the pipe symbol. The logical command would be

 $ grep | .kshrc Usage: grep [OPTION]… PATTERN [FILE]… ksh: .kshrc: command not found

but this doesn’t work. As the error messages indicate, the shell interprets | as an instruction to send the output of the grep command to a (nonexistent) command called ".kshrc”.

One way to get | into the command line as an ordinary character, rather than a special instruction to the shell, is to quote it. Enclosing any symbol or string in single quotes prevents the shell from treating it as a special character. For example,

 $ grep '|' .kshrc alias lc='ls -la | more'

There are two other ways to quote command-line input to protect it from shell interpretation-double quotes (“”) and the backslash character (\):

 $ grep " | " .kshrc

and

 $ grep \ | .kshrc

Double quotes act like single quotes, except that they allow the shell to process the characters used for variable substitution and command substitution. The \ character quotes the character immediately following it. In the preceding example, this causes the shell to treat the | character as a normal character rather than as a command pipe. Compare the following three examples:

 $ grep '$HOME' .profile PATH=$PATH:$HOME/bin $ grep \$HOME .profile PATH=$PATH:$HOME/bin $ grep "$HOME" .profile $

In the first two examples, the single quotes and the backslash remove the special meaning of the $ character. This causes grep to search for the literal string $HOME. In the third example, the double quotes around $HOME allow the shell to substitute the value of the variable. So grep searches for a string like /home/raf, and does not find it in the .profile.

Quoting can also be used to prevent the shell from interpreting white space (blanks, tabs, and newlines) as command-line argument separators. For example, if you want to delete a file named Kili Photo.jpg, with a space in the middle of the filename, you need to group the two words as a single argument, either with quotes

 $ rm "Kili Photo.jpg"

or with a backslash

 $ rm Kili\ Photo.jpg

If you did not quote the filename, rm would attempt to delete two files, Kili and Photo.jpg.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net