There are always three default "files" open, stdin (the keyboard), stdout (the screen), and stderr (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 Example 4-1 and Example 4-2) and sending it as input to another file, command, program, or script.
Each open file gets assigned a file descriptor. [1] The file descriptors for stdin, stdout, and stderr 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 stdin, stdout, or stderr as a temporary duplicate link. [2] This simplifies restoration to normal after complex redirection and reshuffling (see Example 16-1).
1 > 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 >> 14 # Redirect stdout to a file. 15 # Creates the file if not present, otherwise appends to it. 16 17 18 # Single-line redirection commands (affect only the line they are on): 19 # -------------------------------------------------------------------- 20 1>filename 21 # Redirect stdout to file "filename". 22 1>>filename 23 # Redirect and append stdout to file "filename". 24 2>filename 25 # Redirect stderr to file "filename". 26 2>>filename 27 # Redirect and append stderr to file "filename". 28 29 #============================================================================== 30 # Redirecting stdout, one line at a time. 31 LOGFILE=script.log 32 33 echo "This statement is sent to the log file, \"$LOGFILE\"." 1>$LOGFILE 34 echo "This statement is appended to \"$LOGFILE\"." 1>>$LOGFILE 35 echo "This statement is also appended to \"$LOGFILE\"." 1>>$LOGFILE 36 echo "This statement is echoed to stdout, and will not appear in \"$LOGFILE\"." 37 # These redirection commands automatically "reset" after each line. 38 39 40 41 # Redirecting stderr, one line at a time. 42 ERRORFILE=script.errors 43 44 bad_command1 2>$ERRORFILE # Error message sent to $ERRORFILE. 45 bad_command2 2>>$ERRORFILE # Error message appended to $ERRORFILE. 46 bad_command3 # Error message echoed to stderr, 47 #+ and does not appear in $ERRORFILE. 48 # These redirection commands also automatically "reset" after each line. 49 #============================================================================== 50 51 52 53 2>&1 54 # Redirects stderr to stdout. 55 # Error messages get sent to same place as standard output. 56 57 i>&j 58 # Redirects file descriptor i to j. 59 # All output of file pointed to by i gets sent to file pointed to by j. 60 61 >&j 62 # Redirects, by default, file descriptor 1 (stdout) to j. 63 # All stdout gets sent to file pointed to by j. 64 65 0< 66 < 67 # Accept input from a file. 68 # Companion command to ">", and often used in combination with it. 69 # 70 # grep search-word <filename 71 72 73 [j]<>filename 74 # Open file "filename" for reading and writing, and assign file descriptor "j" to it. 75 # If "filename" does not exist, create it. 76 # If file descriptor "j" is not specified, default to fd 0, stdin. 77 # 78 # An application of this is writing at a specified place in a file. 79 echo 1234567890 > File # Write string to "File". 80 exec 3<> File # Open "File" and assign fd 3 to it. 81 read -n 4 <&3 # Read only 4 characters. 82 echo -n . >&3 # Write a decimal point there. 83 exec 3>&- # Close fd 3. 84 cat File # ==> 1234.67890 85 # Random access, by golly. 86 87 88 89 | 90 # Pipe. 91 # General purpose process and command chaining tool. 92 # Similar to ">", but more general in effect. 93 # Useful for chaining commands, scripts, files, and programs together. 94 cat *.txt | sort | uniq > result-file 95 # Sorts the output of all the .txt files and deletes duplicate lines, 96 # finally saves results to "result-file". |
Multiple instances of input and output redirection and/or pipes can be combined in a single command line.
1 command < input-file > output-file 2 3 command1 | command2 | command3 > output-file |
Multiple output streams may be redirected to one file.
1 ls -yz >> command.log 2>&1 2 # Capture result of illegal options "yz" to "ls" in file "command.log". 3 # Because stderr redirected to the file, any error messages will also be there. |
Close input file descriptor n.
Close stdin.
Close output file descriptor n.
Close stdout.
Child processes inherit open file descriptors. This is why pipes work. To prevent an fd from being inherited, close it.
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 'ls' and 'grep'. 5 exec 3>&- # Now close it for the remainder of the script. 6 7 # Thanks, S.C. |
For a more detailed introduction to I/O redirection see Appendix D.
The exec <filename command redirects stdin to a file. From that point on, all stdin comes from that file, rather than its normal source (usually keyboard input). This provides a method of reading a file line by line and possibly parsing each line of input using sed and/or awk.
Example 16-1. Redirecting stdin using exec
1 #!/bin/bash 2 # Redirecting stdin using 'exec'. 3 4 5 exec 6<&0 # Link file descriptor #6 with stdin. 6 7 exec < data-file # stdin replaced by file "data-file" 8 9 read a1 # Reads first line of file "data-file". 10 read a2 # Reads second line of file "data-file." 11 12 echo 13 echo "Following lines read from file." 14 echo "-------------------------------" 15 echo $a1 16 echo $a2 17 18 echo; echo; echo 19 20 exec 0<&6 6<&- 21 # Now restore stdin from fd #6, where it had been saved, 22 # and close fd #6 ( 6<&- ) to free it for other processes to use. 23 # <&6 6<&- also works. 24 25 echo -n "Enter data " 26 read b1 # Now "read" functions as expected, reading from normal stdin. 27 echo "Input read from stdin." 28 echo "----------------------" 29 echo "b1 = $b1" 30 31 echo 32 33 exit 0 |
[1] | A file descriptor is simply a number that the operating system assigns to an open file to keep track of it. Consider it a simplified version of a file pointer. It is analogous to a file handle in C. |
[2] | Using file descriptor 5 might cause problems. When Bash creates a child process, as with exec, the child inherits fd 5 (see Chet Ramey's archived e-mail, SUBJECT: RE: File descriptor 5 is held open). Best leave this particular fd alone. |