📄 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.57"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Beyond the Basics"HREF="part3.html"><LINKREL="PREVIOUS"TITLE="Arithmetic Expansion"HREF="arithexp.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"><TABLEWIDTH="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="arithexp.html">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom"></TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="redircb.html">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="CHAPTER"><H1><ANAME="IO-REDIRECTION">Chapter 16. I/O Redirection</A></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="AEN13085"HREF="#FTN.AEN13085">[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="AEN13095"HREF="#FTN.AEN13095">[2]</A> This simplifies restoration to normal after complex redirection and reshuffling (see <AHREF="io-redirection.html#REDIR1">Example 16-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 #============================================================================== 38 # Redirecting stdout, one line at a time. 39 LOGFILE=script.log 40 41 echo "This statement is sent to the log file, \"$LOGFILE\"." 1>$LOGFILE 42 echo "This statement is appended to \"$LOGFILE\"." 1>>$LOGFILE 43 echo "This statement is also appended to \"$LOGFILE\"." 1>>$LOGFILE 44 echo "This statement is echoed to stdout, and will not appear in \"$LOGFILE\"." 45 # These redirection commands automatically "reset" after each line. 46 47 48 49 # Redirecting stderr, one line at a time. 50 ERRORFILE=script.errors 51 52 bad_command1 2>$ERRORFILE # Error message sent to $ERRORFILE. 53 bad_command2 2>>$ERRORFILE # Error message appended to $ERRORFILE. 54 bad_command3 # Error message echoed to stderr, 55 #+ and does not appear in $ERRORFILE. 56 # These redirection commands also automatically "reset" after each line. 57 #============================================================================== 58 59 60 61 2>&1 62 # Redirects stderr to stdout. 63 # Error messages get sent to same place as standard output. 64 65 i>&j 66 # Redirects file descriptor <ICLASS="EMPHASIS">i</I> to <ICLASS="EMPHASIS">j</I>. 67 # All output of file pointed to by <ICLASS="EMPHASIS">i</I> gets sent to file pointed to by <ICLASS="EMPHASIS">j</I>. 68 69 >&j 70 # Redirects, by default, file descriptor <ICLASS="EMPHASIS">1</I> (stdout) to <ICLASS="EMPHASIS">j</I>. 71 # All stdout gets sent to file pointed to by <ICLASS="EMPHASIS">j</I>. 72 73 0< FILENAME 74 < FILENAME 75 # Accept input from a file. 76 # Companion command to <SPANCLASS="QUOTE">">"</SPAN>, and often used in combination with it. 77 # 78 # grep search-word <filename 79 80 81 [j]<>filename 82 # Open file "filename" for reading and writing, and assign file descriptor "j" to it. 83 # If "filename" does not exist, create it. 84 # If file descriptor "j" is not specified, default to fd 0, stdin. 85 # 86 # An application of this is writing at a specified place in a file. 87 echo 1234567890 > File # Write string to "File". 88 exec 3<> File # Open "File" and assign fd 3 to it. 89 read -n 4 <&3 # Read only 4 characters. 90 echo -n . >&3 # Write a decimal point there. 91 exec 3>&- # Close fd 3. 92 cat File # ==> 1234.67890 93 # Random access, by golly. 94 95 96 97 | 98 # Pipe. 99 # General purpose process and command chaining tool. 100 # Similar to <SPANCLASS="QUOTE">">"</SPAN>, but more general in effect. 101 # Useful for chaining commands, scripts, files, and programs together. 102 cat *.txt | sort | uniq > result-file 103 # Sorts the output of all the .txt files and deletes duplicate lines, 104 # 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 12-28</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> </P><P>For a more detailed introduction to I/O redirection see <A
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -