📄 unx13.htm
字号:
ch2.txt
mkdir $tmpfile || exit</PRE>
<H4 ALIGN="CENTER">
<CENTER><A ID="I19" NAME="I19">
<FONT SIZE=3><B>Redirecting Input and Output</B>
<BR></FONT></A></CENTER></H4>
<P>C shell provides several commands for redirecting the input and output of commands. You might already be familiar with the input (<) or output (>) redirection characters from earlier chapters. C shell provides you with these and more.
<BR></P>
<P>An I/O redirection is an instruction to the shell you append to a command. It causes one of the standard file descriptors to be assigned to a specific file. You might have previously encountered standard files in the discussion of the Bourne shell
(Chapter 11). The UNIX operating system defines three standard file descriptors: standard input, standard output, and standard error. (These names are sometimes abbreviated to stdin, stdout, and stderr.)
<BR></P>
<HR ALIGN=CENTER>
<NOTE>
<IMG SRC="note.gif" WIDTH = 35 HEIGHT = 35><B>NOTE:</B> The UNIX operating system actually provides at least twenty-five file descriptors for use by a command. It is only by convention that the first three are set aside for reading input, writing output,
and printing error messages. Unless you instruct otherwise, the shell always opens these three file descriptors before executing a command, and assigns them all to your terminal.
<BR></NOTE>
<HR ALIGN=CENTER>
<P>A file descriptor is not the file itself. Rather, it is a channel, much like the phone jack on the back of your stereo: you can connect it to any audio source you like. Similarly, a file descriptor such as standard input must be connected to a
file—your terminal by default, or the disk file or readable device of your choice.
<BR></P>
<P>You can change the location where a command reads data, writes output, and prints error messages, using one or more of the I/O redirection operators. The operators are shown in Table 13.2.
<BR></P>
<UL>
<LH><B>Table 13.2. I/O redirection operators.</B>
<BR></LH></UL>
<TABLE BORDER>
<TR>
<TD>
<PRE><I>Format</I>
<BR></PRE>
<TD>
<PRE><I>Effect</I>
<BR></PRE>
<TR>
<TD COLSPAN=2>
<P><I>Input Redirection</I></P>
<TR>
<TD>
<P>< <I>filename</I></P>
<TD>
<P>Use the contents of filename as input to a command.</P>
<TR>
<TD>
<P><< <I>word</I></P>
<TD>
<P>Provide shell input lines as command input. Lines of the shell input which follow the line containing this redirection operator are read and saved by the shell in a temporary file. Reading stops when the shell finds a line beginning with word. The saved
lines then become the input to the command. Of course, the lines read and saved are effectively deleted from the shell input, and will not be executed as commands; they are effectively "eaten" by the << operator. Shell execution continues
with the line following the line beginning with word. If you use the << operator on a command you type at the terminal, be careful: lines you type afterward will be gobbled up by the shell—not executed—until you enter a line begining with
whatever you specified as word. The << operator is most often used in shell scripts.</P>
<TR>
<TD COLSPAN=2>
<P ALIGN="CENTER">
<CENTER><B>Output Redirection</B></CENTER></P>
<TR>
<TD>
<P>> <I>filename</I></P>
<TD>
<P>Write command output to <I>filename</I></P>
<TR>
<TD>
<P>>! <I>filename</I></P>
<TD>
<P>Write command output to filename, and ignore the noclobber option. The noclobber option is fully explained in the section "Using Predefined Variables" later in this chapter. Briefly it causes the shell to disallow the > filename redirection
when filename already exists; noclobber is therefore a safety you can use to prevent your accidentally destroying an existing file. Of course, sometimes you want to redirect output to a file even though it already exists. In such a case, you must use the
>! operator to tell the shell you really want to proceed with the redirection. If you don't set the noclobber option, then you won't need to use the >! operator either.</P>
<TR>
<TD>
<P>>& <I>filename</I></P>
<TD>
<P>Open filename and write both the command output and error messages to it</P>
<TR>
<TD>
<P>>&! <I>filename</I></P>
<TD>
<P>Open filename and write both the command output and error messages to it, and ignore the noclobber option</P>
<TR>
<TD>
<P>>> <I>filename</I></P>
<TD>
<P>Open filename and write command output at the end of the file (append mode)</P>
<TR>
<TD>
<P>>>! <I>filename</I></P>
<TD>
<P>Open <I>filename</I> and write command output at the end of the file (append mode), and ignore the noclobber option</P>
<TR>
<TD>
<P>>>& <I>filename</I></P>
<TD>
<P>Open filename and write command output and error messages at the end of the file (append mode)</P>
<TR>
<TD>
<P>>>&! <I>filename</I></P>
<TD>
<P>Open <I>filename</I> and write command output and error messages at the end of the file (append mode), and ignore the noclobber option</P></TABLE>
<P>In Table 13.2, <I>filename</I> represents any ordinary filename or pathname, or any filename or pathname resulting after variable substitution, command substitution, or filename generation.
<BR></P>
<P>I/O redirection operators are appended to a command; for example, date >curdate will write the current date to the file curdate instead of to your terminal. You can also use more than one redirection per command: simply list them one after another at
the end of the command. The order doesn't matter: for example, both cat <infile >outfile and cat >outfile <bigfile will have the same effect.
<BR></P>
<H5 ALIGN="CENTER">
<CENTER><A ID="I20" NAME="I20">
<FONT SIZE=3><B>Input Redirection</B>
<BR></FONT></A></CENTER></H5>
<P>Some commands make no special use of the standard input file, such as the date and the ls system commands; others require an input file to function properly, such as the cat and awk commands. You can use the < redirection operator in the form command
<I>< </I>filename to designate a file as the source of input for commands like cat and awk; if you do not, these commands will read data from your keyboard—sometimes useful, but usually not. If you provide an input redirection, but the command does
not read data (such as ls), the I/O redirection is still performed by the shell, it is just ignored by the command.
<BR></P>
<P>It is an error to redirect standard input to a file that doesn't exist.
<BR></P>
<P>The redirection << <I>word</I> is a special form of the input redirection operator. Rather than taking input from a file, input to the command comes from the current shell input stream—your keyboard, if you append << to a command you
type in, or your shell script if you use << on a command in a shell script.
<BR></P>
<P>For word, you choose an arbitrary string to delimit the lines of input. Then write the lines to be provided to the command as input immediately following the command line, and follow the last line with a line beginning with word. The shell reads the
lines ahead, stores them in a temporary file, and sets up the temporary file as standard input for the command.
<BR></P>
<P>This form of input redirection is called a here document, because it is located here, in line with your shell commands. It is useful when you want to provide predefined data to a command, and it saves you from having to create a file to hold the data.
<BR></P>
<P>Unlike the <I>filename</I> part of other I/O redirection operators, word for the here document is not scanned for variable references, command substitutions, or filename patterns; it is used as is. Also, the following shell input lines are checked for
the presence of word as the first word of the line before any substitutions or replacements are performed on the line.
<BR></P>
<P>Normally, lines of the here document are checked for variable references and command replacements; this allows you to encode variable information in the here document. If you quote any part of word, however, the lines are read and passed to the command
without modification. For example, the redirection << STOP reads lines up to STOP, and performs substitutions on the lines it reads; the redirection << "STOP" reads lines up to the line beginning with STOP, and passes the lines
directly to the command, as is, without substitutions or replacements of any kind.
<BR></P>
<P>The line beginning with word is discarded, and neither passed to the command in the here document, nor executed by the shell.
<BR></P>
<P>The following example shows the use of a here document to print a customized message:
<BR></P>
<PRE>pr << HERE | lp
Hello, $user.
Your print job,
'lpstat'
has been scheduled for output at a later time.
Please contact Joe if you have any questions.
HERE</PRE>
<P>The line containing the word <I>HERE</I> will not appear in the output message; it is simply a mark to let the shell know where the redirected lines end.
<BR></P>
<H5 ALIGN="CENTER">
<CENTER><A ID="I21" NAME="I21">
<FONT SIZE=3><B>Output Redirection</B>
<BR></FONT></A></CENTER></H5>
<P>Output redirections have the general form > and >>. The first operator creates a new file of the specified name. The file is opened before command execution begins, so even if the command fails, or cannot be found, or if the shell finds an
error on the command line and stops, the output file will still be created.
<BR></P>
<P>If you've set the noclobber option (with set noclobber), then the shell will refuse to create the named output file if it already exists; doing so would destroy its current contents. If you want to perform the output redirection even if the file
<I>filename</I> already exists, use the redirection operator >! instead; it overrides the noclobber option.
<BR></P>
<P>The >> command arranges for command output to be added to the end of the named file. For this redirection operator, the noclobber option requires that the named file already exist. If you use the alternate form >>!, or if you use >>
and the noclobber option is not set, the shell will create the named file if necessary.
<BR></P>
<P>The >& and >>& operators redirect both the standard output and standard error files to <I>filename</I>. The Bourne shell allows you to redirect the standard output and standard error files separately; the C shell does not. Actually,
this is not much of a limitation in real life.
<BR></P>
<P>If you have the noclobber option set, you'll need to use >&! instead of >& to proceed even if the named file exists, or >>&! to proceed even if the named file doesn't exist.
<BR></P>
<HR ALIGN=CENTER>
<NOTE>
<IMG SRC="note.gif" WIDTH = 35 HEIGHT = 35><B>NOTE:</B> For purposes of understanding shell syntax, it might be noted that appending an I/O redirection to a simple command yields a simple command. Except where specifically prohibited, a command with
redirections appended can be used wherever a simple command is allowed, such as on the single-line if statement.
<BR></NOTE>
<HR ALIGN=CENTER>
<H4 ALIGN="CENTER">
<CENTER><A ID="I22" NAME="I22">
<FONT SIZE=3><B>Quoting or Escaping from Special Characters</B>
<BR></FONT></A></CENTER></H4>
<P>As you've seen from previous sections, certain characters have special meaning for the shell. That is, when the shell encounters a special character, it will perform the action that the special character calls for. The following punctuation characters
available on the standard keyboard are special to the shell and disrupt the scanning of ordinary words:
<BR></P>
<PRE>~ ' ! @ # $ % ^ & * ( ) \ | { } [ ] ; ' " < > ?</PRE>
<P>In some contexts, particularly within the switch statement, the : (colon) is also a special character. The colon is recognized as a special character only when expected, in a case or default statement, and as a statement label. It does not need to be
quoted except to avoid these specific interpretations.
<BR></P>
<P>To use one of these characters as a part of a word without its special significance, you can escape the character by placing a backslash (\) immediately in front of the character. Note that a backslash intended as an ordinary character must be written
as two backslashes in succession: \\. To escape a two-character operator such as >>, you must insert a backslash in front of each character: \>\>.
<BR></P>
<P>Alternatively, you can enclose the special character or any portion of the word containing the character in quotes. The shell recognizes three kinds of quotes: the apostrophe ('), the quote ("), and the backquote (`).
<BR></P>
<P>Use two apostrophes (also called single quotes) to enclose a character sequence and avoid all interpretation by the shell. I often call a string enclosed in apostrophes a hard-quoted string, because the shell performs absolutely no substitution,
replacement, or special interpretation of anything appearing between the apostrophes. Even the backslash character is treated as an ordinary character, so there are no escapes within an apostrophe-enclosed string, and you cannot embed an apostrophe in such
a string. That is, the string 'who's there' will cause a shell error: the shell will see this as who concatenated with an s, followed by a white space delimiter, followed by a word beginning with there, and then the starting apostrophe of another string.
The third apostrophe starts a quoted string that the shell will follow over as many lines as necessary to find an ending apostrophe, probably eating up shell lines you intended as commands, and eventually yielding a shell syntax error or an erroneous
command execution.
<BR></P>
<P>One of the uses of quoted strings is to specify a single word containing blanks, tabs, and newline characters. For example, the following shows the use of a single echo command to print two lines of output:
<BR></P>
<PRE>% echo -n 'Hello.
Please enter your name: '
Hello.
Please enter your name:</PRE>
<P>The double apostrophe or quote (") also provides a special bracket for character strings. Like the apostrophe, the quote hides most special characters from the shell's observation. Quoted strings, however, are subject to two kinds of scan and
replacement: variable references and command substitutions.
<BR></P>
<P>Any of the reference forms for shell variables ($1, $<I>name</I>, ${name}, $<I>name</I>[<I>index</I>], $*, and others) are recognized inside quoted strings and are replaced with the corresponding string value. The replacement occurs inside the quoted
string, leaving its unity as a single word intact (even if the substituted value includes blanks, tabs, or newline characters).
<BR></P>
<P>Command substitution occurs for strings enclosed in backquotes ('). The entire string enclosed between matching backquotes is extracted and executed by the shell as if it were an independent command. The command can be two or more commands separated
with semicolons, or a pipeline, or any form of compound statement. Any data written to standard output by the command is captured by the shell and becomes the string value of the backquoted command. The string value is parsed into words, and the series of
words replaces the entire backquoted string.
<BR></P>
<P>All forms of shell substitution will occur inside backquoted command strings, including variable replacement, nested command executions, history substitutions, and filename patterns. Nested command strings will work, but the backquotes introducing them
must be escaped with \ to hide them from the shell's first scan of the backquoted string.
<BR></P>
<P>A backquoted command string (or any number of them) can appear inside a quoted string and will have its normal effect; this is the second form of substitution performed on "-quoted strings. A quoted command substitution
("<I>xxx</I>`<I>commands</I>`<I>xxx</I>") generates new words only at the end of each line, except at the end of the last line. If the executed command prints only one line of text, the text replaces the backquoted expression without introducing
any word breaks.
<BR></P>
<P>Both quoting forms '...' and "..." suppress filename generation. For example, note the difference in the following echo commands:
<BR></P>
<PRE>% echo *.c
main.c io.c parse.c math.c
% echo "*.c"
*.c</PRE>
<P>Apostrophes and quotes can appear inside a double-quoted string. The double quote must be escaped with a backslash to prevent premature termination of the quoted string (for example "He said, \"John!\""). The apostrophe has no
special significance when appearing inside a double-quoted string and does not need to be backslashed. The following example shows the use of quotes inside quoted strings:
<BR></P>
<PRE>% echo "He said, \"John!\""
He said, "John!"
% echo "Filename: '$1'"
Filename: '/usr/bin/ls'</PRE>
<P>A backslash appearing inside an apostrophe-quoted string is retained and appears in the string's value, because no substitutions occur inside an apostrophe-quoted string. Inside a double-quoted string or a command substitution using ', or in a normal
unquoted word, a backslash has the effect of suppressing shell interpretation of the character that follows it; the backslash is then removed from the string. The following examples show the effect of a backslash in all these contexts:
<BR></P>
<PRE>% echo "Double \" quote"
Double " quote
% echo Double \" quote
Double " quote
% echo 'Single \' quote
Single \ quote
% echo Single \' quote
Single ' quote</PRE>
<H4 ALIGN="CENTER">
<CENTER><A ID="I23" NAME="I23">
<FONT SIZE=3><B>Working with Directories and the Directory Stack</B>
<BR></FONT></A></CENTER></H4>
<P>C shell provides you with several built-in commands for working with directories. The cd, chdir, pushd, and popd commands all change the current directory i
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -