Input and Output (I/O)

As the title of this section suggests, I/O stands for input/output. Your commands or programs will often have input and/or output. It is important to know how to specify where your input is from or to redirect where output should go; for example, you may want your output to go to a file rather than printing to the screen. Inputs and outputs of a program are called streams in Linux. There are three types of streams:

stdin
standard input - the stream of data going into a program. By default, this is input from the keyboard.
stdout
standard output - the output stream where data is written out by a program. By default, this output is sent to the screen.
stderr
standard error - another output stream (independent of stdout) where programs output error messages. By default, error output is sent to the screen.
Output Redirection

It is often useful to save the output (stdout) from a program to a file. This can be done with the redirection operator >.

For another example, imagine that you run the ls command on a directory that has so many files that your screen scrolls and you cannot see all of the files listed. You might want to redirect that output to a file so you can open it up in a text editor and look more closely at the output:

Redirection of this sort will create the named file if it doesn't exist, or else overwrite the existing file of the same name. If you know the file already exists (or even if it does not), you can append the output file instead of rewriting it using the redirection operator >>.

Input Redirection

Input can also be given to a command from a file instead of typing it in the shell by using the redirection operator <.

Alternatively, you can use the pipe operator | like this:

Using the pipe operator |, you can link commands together. The pipe will link stdout from one command to stdin of another command. In the above example, we use the cat command to print the file to the screen (stdout), and then we redirect that printing to the command mycommand.

Error Redirection

When performing normal redirection of the standard output of a program (stdout), stderr will not be redirected because it is a separate stream. Many programmers find it useful to redirect only stderr to a separate file. You might do this to make it easier to find the error messages from your program. This can be accomplished in the shell with a redirection operator 2>.

In addition, you can merge stderr with stdout by using 2>&1.

Redirect and Save Output

Redirecting the output of a command to a file is useful, but it means that you will not see anything on the screen while it is running. This can be undesirable, especially for long-running commands. To have the output go to both a file and the screen, use the tee command:

You can also use tee to catch stderr with:

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement