Advanced Bash-Scripting HOWTO: A guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 3. Tutorial / Reference | Next |
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 the output of a file, command, program, or script 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. Opening additional files assigns descriptors 3 to 9. It is sometimes useful to assign one of these additional file descriptors to stdout or stderr as a temporary duplicate copy. This simplifies restoration to normal after complex redirection and reshuffling.
> # Redirect stdout to a file. # Creates the file if not present, otherwise overwrites it. ls -lR > dir-tree.list # Creates a file containing a listing of the directory tree. >> # Redirect stdout to a file. # Creates the file if not present, otherwise appends to it. 2> &1 # Redirects stderr to stdout. # Has the effect of making visible error messages that might otherwise not be seen. i> &j # Redirects file descriptor i to j # All output of file pointed to by i gets sent to file pointed to by j < # Accept input from a file. # Companion command to ">", and often used in combination with it. grep search-word <filename | # Pipe. # General purpose process and command chaining tool. # Similar to ">", but more general in effect. # Useful for chaining commands, scripts, files, and programs together. cat *.txt | sort | uniq > result-file # Sorts the output of all the .txt files and deletes duplicate lines, # finally saves results to "result-file". |
Note: Multiple instances of input and output redirection and/or pipes can be combined in a single command line.
command < input-file > output-file command1 | command2 | command3 > output-file |
close input file descriptor n
close stdin
close output file descriptor n
close stdout
[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. |