Input-Output redirection

When a command is started under Linux it has three data streams associated with it: standard input (stdin), standard output (stdout), and standard error (stderr). The corresponding file streams are numbered are 0, 1 and 2. Initially all these data streams are connected to the terminal.

A terminal is also a type of file in Linux. Most of the commands take input from the terminal and produce output on the terminal. In most cases we can replace the terminal with a file for either or both of input and output. For example:

ls > listfile

puts the listing of files in the current directory in the file listfile. The symbol > means redirect the standard output to the following file, rather than sending to the terminal.

The symbol » operates just as >, but appends the output to the contents of the filelistfile instead of creating a new file. Similarly, the symbol < means to take the standard input for a program from the following file, instead of from a terminal. For example:

mail -s "program status report" mary joe tom < letter

mails the contents of the file letter to the three users: mary, joe and tom. A Java (or any other) program that reads input from the keyboard can be redirected to read from a file as follows:

java GetInput < input.txt

To redirect error messages (which are sent on stderr with file descriptor 2) see the following:

javac BadProgram.java 2> error.log

Or if you want both the output and the error messages to go to a file, see the following:

javac BadProgram.java > log 2>&1