8.9 Input and Output Redirection
As previously mentioned, many shell commands output information when executed. By default this output goes to a device file called stdout which is essentially the terminal window or console in which the shell is running. Conversely, the shell takes input from a device file named stdin, which by default is the keyboard.
Output from a command can be redirected from stdout to a physical file on the file system using the ‘>’ character. For example, to redirect the output from an ls command to a file named files.txt, the following command would be required:
$ ls *.txt > files.txt
Upon completion, files.txt will contain the list of files in the current directory. Similarly, the contents of a file may be fed into a command in place of stdin. For example, to redirect the contents of a file as input to a command:
$ wc –l < files.txt
The above command will display the number of lines contained in the files.txt file.
It is important to note that the ‘>’ redirection operator creates a new file, or truncates an existing file when used. In order to append to an existing file, use the ‘>>’ operator:
$ ls *.dat >> files.txt
In addition to standard output, the shell also provides standard error output using stderr. While output from a command is directed to stdout, any error messages generated by the command are directed to stderr. This means that if stdout is directed to a file, error messages will still appear in the terminal. This is generally the desired behavior, though stderr may also be redirected if desired using the ‘2>’ operator:
$ ls dkjfnvkjdnf 2> errormsg
On completion of the command, an error reporting the fact that the file named dkjfnvkjdnf could not be found will be contained in the errormsg file.
Both stderr and stdout may be redirected to the same file using the &> operator:
$ ls /etc dkjfnvkjdnf &> alloutput
On completion of execution, the alloutput file will contain both a listing of the contents of the /etc directory, and the error message associated with the attempt to list a non-existent file.