📄 io-redirection.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>I/O Redirection</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Advanced Topics"HREF="part5.html"><LINKREL="PREVIOUS"TITLE="Here Documents"HREF="here-docs.html"><LINKREL="NEXT"TITLE="Redirecting Code Blocks"HREF="redircb.html"><METAHTTP-EQUIV="Content-Style-Type"CONTENT="text/css"><LINKREL="stylesheet"HREF="common/kde-common.css"TYPE="text/css"><METAHTTP-EQUIV="Content-Type"CONTENT="text/html; charset=iso-8859-1"><METAHTTP-EQUIV="Content-Language"CONTENT="en"><LINKREL="stylesheet"HREF="common/kde-localised.css"TYPE="text/css"TITLE="KDE-English"><LINKREL="stylesheet"HREF="common/kde-default.css"TYPE="text/css"TITLE="KDE-Default"></HEAD><BODYCLASS="CHAPTER"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#AA0000"VLINK="#AA0055"ALINK="#AA0000"STYLE="font-family: sans-serif;"><DIVCLASS="NAVHEADER"><TABLESUMMARY="Header navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><THCOLSPAN="3"ALIGN="center">Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH></TR><TR><TDWIDTH="10%"ALIGN="left"VALIGN="bottom"><AHREF="here-docs.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom"></TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="redircb.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="CHAPTER"><H1><ANAME="IO-REDIRECTION"></A>Chapter 19. I/O Redirection</H1><P><ANAME="IOREDIRREF"></A></P><P>There are always three default <SPANCLASS="QUOTE">"files"</SPAN> open, <TTCLASS="FILENAME">stdin</TT> (the keyboard), <TTCLASS="FILENAME">stdout</TT> (the screen), and <TTCLASS="FILENAME">stderr</TT> (error messages output to the screen). These, and any other open files, can be redirected. Redirection simply means capturing output from a file, command, program, script, or even code block within a script (see <AHREF="special-chars.html#EX8">Example 3-1</A> and <AHREF="special-chars.html#RPMCHECK">Example 3-2</A>) and sending it as input to another file, command, program, or script.</P><P><ANAME="FDREF"></A>Each open file gets assigned a file descriptor. <ANAME="AEN16482"HREF="#FTN.AEN16482">[1]</A> The file descriptors for <TTCLASS="FILENAME">stdin</TT>, <TTCLASS="FILENAME">stdout</TT>, and <TTCLASS="FILENAME">stderr</TT> are 0, 1, and 2, respectively. For opening additional files, there remain descriptors 3 to 9. It is sometimes useful to assign one of these additional file descriptors to <TTCLASS="FILENAME">stdin</TT>, <TTCLASS="FILENAME">stdout</TT>, or <TTCLASS="FILENAME">stderr</TT> as a temporary duplicate link. <ANAME="AEN16494"HREF="#FTN.AEN16494">[2]</A> This simplifies restoration to normal after complex redirection and reshuffling (see <AHREF="io-redirection.html#REDIR1">Example 19-1</A>).</P><P><ANAME="IOREDIRECTIONREF"></A></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 COMMAND_OUTPUT > 2 # Redirect stdout to a file. 3 # Creates the file if not present, otherwise overwrites it. 4 5 ls -lR > dir-tree.list 6 # Creates a file containing a listing of the directory tree. 7 8 : > filename 9 # The > truncates file "filename" to zero length. 10 # If file not present, creates zero-length file (same effect as 'touch'). 11 # The : serves as a dummy placeholder, producing no output. 12 13 > filename 14 # The > truncates file "filename" to zero length. 15 # If file not present, creates zero-length file (same effect as 'touch'). 16 # (Same result as ": >", above, but this does not work with some shells.) 17 18 COMMAND_OUTPUT >> 19 # Redirect stdout to a file. 20 # Creates the file if not present, otherwise appends to it. 21 22 23 # Single-line redirection commands (affect only the line they are on): 24 # -------------------------------------------------------------------- 25 26 1>filename 27 # Redirect stdout to file "filename." 28 1>>filename 29 # Redirect and append stdout to file "filename." 30 2>filename 31 # Redirect stderr to file "filename." 32 2>>filename 33 # Redirect and append stderr to file "filename." 34 &>filename 35 # Redirect both stdout and stderr to file "filename." 36 # 37 # Note that &>>filename 38 #+ -- attempting to redirect and *append* 39 #+ stdout and stderr to file "filename" -- 40 #+ fails with the error message, 41 #+ syntax error near unexpected token `>'. 42 43 M>N 44 # "M" is a file descriptor, which defaults to 1, if not explicitly set. 45 # "N" is a filename. 46 # File descriptor "M" is redirect to file "N." 47 M>&N 48 # "M" is a file descriptor, which defaults to 1, if not set. 49 # "N" is another file descriptor. 50 51 #============================================================================== 52 53 # Redirecting stdout, one line at a time. 54 LOGFILE=script.log 55 56 echo "This statement is sent to the log file, \"$LOGFILE\"." 1>$LOGFILE 57 echo "This statement is appended to \"$LOGFILE\"." 1>>$LOGFILE 58 echo "This statement is also appended to \"$LOGFILE\"." 1>>$LOGFILE 59 echo "This statement is echoed to stdout, and will not appear in \"$LOGFILE\"." 60 # These redirection commands automatically "reset" after each line. 61 62 63 64 # Redirecting stderr, one line at a time. 65 ERRORFILE=script.errors 66 67 bad_command1 2>$ERRORFILE # Error message sent to $ERRORFILE. 68 bad_command2 2>>$ERRORFILE # Error message appended to $ERRORFILE. 69 bad_command3 # Error message echoed to stderr, 70 #+ and does not appear in $ERRORFILE. 71 # These redirection commands also automatically "reset" after each line. 72 #=======================================================================</PRE></TD></TR></TABLE><P><ANAME="IOREDIRECTIONREF1"></A></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 2>&1 2 # Redirects stderr to stdout. 3 # Error messages get sent to same place as standard output. 4 5 i>&j 6 # Redirects file descriptor <SPANCLASS="emphasis"><ICLASS="EMPHASIS">i</I></SPAN> to <SPANCLASS="emphasis"><ICLASS="EMPHASIS">j</I></SPAN>. 7 # All output of file pointed to by <SPANCLASS="emphasis"><ICLASS="EMPHASIS">i</I></SPAN> gets sent to file pointed to by <SPANCLASS="emphasis"><ICLASS="EMPHASIS">j</I></SPAN>. 8 9 >&j 10 # Redirects, by default, file descriptor <SPANCLASS="emphasis"><ICLASS="EMPHASIS">1</I></SPAN> (stdout) to <SPANCLASS="emphasis"><ICLASS="EMPHASIS">j</I></SPAN>. 11 # All stdout gets sent to file pointed to by <SPANCLASS="emphasis"><ICLASS="EMPHASIS">j</I></SPAN>.</PRE></TD></TR></TABLE><P><ANAME="IOREDIRECTIONREF2"></A></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 0< FILENAME 2 < FILENAME 3 # Accept input from a file. 4 # Companion command to <SPANCLASS="QUOTE">">"</SPAN>, and often used in combination with it. 5 # 6 # grep search-word <filename 7 8 9 [j]<>filename 10 # Open file "filename" for reading and writing, 11 #+ and assign file descriptor "j" to it. 12 # If "filename" does not exist, create it. 13 # If file descriptor "j" is not specified, default to fd 0, stdin. 14 # 15 # An application of this is writing at a specified place in a file. 16 echo 1234567890 > File # Write string to "File". 17 exec 3<> File # Open "File" and assign fd 3 to it. 18 read -n 4 <&3 # Read only 4 characters. 19 echo -n . >&3 # Write a decimal point there. 20 exec 3>&- # Close fd 3. 21 cat File # ==> 1234.67890 22 # Random access, by golly. 23 24 25 26 | 27 # Pipe. 28 # General purpose process and command chaining tool. 29 # Similar to <SPANCLASS="QUOTE">">"</SPAN>, but more general in effect. 30 # Useful for chaining commands, scripts, files, and programs together. 31 cat *.txt | sort | uniq > result-file 32 # Sorts the output of all the .txt files and deletes duplicate lines, 33 # finally saves results to <SPANCLASS="QUOTE">"result-file"</SPAN>.</PRE></TD></TR></TABLE><P>Multiple instances of input and output redirection and/or pipes can be combined in a single command line. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 command < input-file > output-file 2 3 command1 | command2 | command3 > output-file</PRE></TD></TR></TABLE> See <AHREF="filearchiv.html#DERPM">Example 15-30</A> and <AHREF="contributed-scripts.html#FIFO">Example A-15</A>.</P><P>Multiple output streams may be redirected to one file. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 ls -yz >> command.log 2>&1 2 # Capture result of illegal options "yz" in file "command.log." 3 # Because stderr is redirected to the file, 4 #+ any error messages will also be there. 5 6 # Note, however, that the following does *not* give the same result. 7 ls -yz 2>&1 >> command.log 8 # Outputs an error message and does not write to file. 9 10 # If redirecting both stdout and stderr, 11 #+ the order of the commands makes a difference.</PRE></TD></TR></TABLE></P><DIVCLASS="VARIABLELIST"><P><B><ANAME="CFD"></A>Closing File Descriptors</B></P><DL><DT><SPANCLASS="TOKEN">n<&-</SPAN></DT><DD><P>Close input file descriptor <TTCLASS="REPLACEABLE"><I>n</I></TT>.</P></DD><DT><SPANCLASS="TOKEN">0<&-</SPAN>, <SPANCLASS="TOKEN"><&-</SPAN></DT><DD><P>Close <TTCLASS="FILENAME">stdin</TT>.</P></DD><DT><SPANCLASS="TOKEN">n>&-</SPAN></DT><DD><P>Close output file descriptor <TTCLASS="REPLACEABLE"><I>n</I></TT>.</P></DD><DT><SPANCLASS="TOKEN">1>&-</SPAN>, <SPANCLASS="TOKEN">>&-</SPAN></DT><DD><P>Close <TTCLASS="FILENAME">stdout</TT>.</P></DD></DL></DIV><P>Child processes inherit open file descriptors. This is why pipes work. To prevent an fd from being inherited, close it. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 # Redirecting only stderr to a pipe. 2 3 exec 3>&1 # Save current "value" of stdout. 4 ls -l 2>&1 >&3 3>&- | grep bad 3>&- # Close fd 3 for 'grep' (but not 'ls'). 5 # ^^^^ ^^^^ 6 exec 3>&- # Now close it for the remainder of the script. 7 8 # Thanks, S.C.</PRE></TD></TR></TABLE
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -