Getting Started : Redirecting Standard Input and Output

Unix has the concept of a standard input (that is, where the input for a command comes from) and a standard output (that is, where the results of a command will go to). By default, both of these are the terminal; the keyboard for the standard input and the screen for the standard output. It is possible to redirect either or both of the standard input and output, using the redirection symbols < and >.

Redirecting Output (>)

This is probably the more commonly used of the two redirection symbols, and can be used to store the results of a command that would normally be displayed on the terminal screen, in a file.

Example

% ls > mydir

The ls command produces a list of files in the current directory. The redirection symbol places this list into the file named mydir.

Redirecting Input (<)

This redirection allows a program that normally takes its input from the terminal keyboard to take it instead from a file.

Example

% maple < run1

This would use the file run1 as the input to the Maple program.

Pipelining

It is often required to send the output of one program as the input of another. This could be done using an intermediate file:

program1 > temp_file
program2 < temp_file

but a more elegant solution is to use a mechanism called a pipe. The sequence above could be rewritten:

program1 | program2

In other words, send the output of program1 as the input of program2. For example, to print a directory listing of all files, the following commands could be used:

% ls -l > list_of_files
% lpr list_of_files

Piping makes the solution much more concise:

% ls -l | lpr

Note, the commands in a pipeline all execute together. As soon as one program in the pipeline generates a chunk of output, the next stage reads it and gets on with processing it.

Important!

It is important to distinguish when input to a command needs to be redirected and when no redirection is required. For example, the command more expects input from a file, given as an argument, i.e. more document.txt. To scroll through output from a command (say a long directory listing) then the output of ls -l must be piped as the input to more, i.e. ls -l | more. The following commands are incorrect:

ls -l > more would create a file called more, containing the directory listing, instead of sending it as input to the command more

more < ls -l would try to find a file called 'ls' to send as input to more

Help: for more information see csh(1). Once in the manual pages type /pipeline to search forward through the screens.