Redirecting standard input and output

Unix considers any device attached to the system to be a file. And that includes your terminal!

By default, a command treats your terminal as the standard input file from which to read in information. Your terminal is also treated as the standard output file to which information is sent from the command.

This action can be changed by redirecting standard input and standard output from and to any other file.


Redirecting standard input

To redirect the standard input for a command use the < (less than) character followed by the name of the input file. For example:

   mail tony < memo

This redirects the standard input to the mail command so that it comes from the file memo. The effect of this is to mail the contents of this file to the user tony.


Redirecting standard output

To redirect the standard output from a command use the > (greater than) symbol followed by the name of the output file. If the file that you redirect standard output to does not already exist it will be created. For example:

   grep Smith names > popular

This redirects the standard output from the grep command so that it goes to the file popular. This file will contain all occurrences of the string Smith that were found in the file called names.

**Caution**

Redirecting standard output to a file that already exists overwrites its contents with the standard output. To prevent this happening, use the shell variable noclobber.


Appending standard output to a file

To append the standard output from a command to a file use two >> (greater than) symbols followed by the name of the file. If the file does not exist it is created. For example:

   cat part1 part2 part3 part4 >> chapt2

This reads files part1 through part4 in turn and appends them to the file chapt2. The contents of part2 are appended to part1 and so on.