I/O redirection

Linux allocates three I/O streams for each process: the standard input, the standard input, and the standard error, which are associated with the descriptors 0,1 and 2, respectively. By default, the standard output and the standard error are tied to the user's screen. Thus, if you type the "cat" command followed by a nonexistent filename, you will see the following error message on your screen:

$cat nonexistentfile cat : nonexistentfile not found

It is possible to redirect the standard error and the standard output to separate destinations. For example, you can direct all error messages to a file for future reference.

Redirecting Standard Output To redirect the standard output, use the > operator followed by the destination file or device. The following cat command direct the output to a file called mylog:

$ cat intro >mylog

Notice that by default, the > operator redirects the standard output. Therefore, error messages resulting from the command above will still appear on the screen. In other words, the command:

$ cat intro >mylog

is interpreted as:

$ cat intro 1> mylog

Redirecting Standard Error To redirect the standard, use the following command:

$ cat intro 2> errlog

In this case, all error messages are written to the file errlog. If you wish to redirect error messages to a specific terminal, you can do it like this:

$cat doc > /dev/tty13

As with other shell commands, you may run the cat command in the background by appending an ampersand at the end:

$cat doc > /dev/tty13 &

The same effect of redirecting the standard error to a device or a file can be achieved by using the >> operator too. For example:

$ cat intro 2>> errlog

Redirecting Standard Input As previously noted, the standard input is associated with the user's keyboard. You can override this setting by like this:

$ tolowercase <mydocument

In this example, the program tolowercase reads its input from the file mydocument rather than the keyboard. Note that the program itself isn't aware that its standard input has been redirected. Furthermore, the string "<mydocument" is not included in the command line arguments passed in argv. Consequently, every scanf(), getch(), and similar syscalls will read their data from mydocument.

Infographic: Starting salaries for computer science grads
View Comments
You Might Like
Join the discussion
Be the first to comment on this article. Our Commenting Policies