Examples of input/output redirection



Last revision August 2, 2004

Table of Contents:

  1. The Unix file system
  2. The directory tree
  3. File ownership and permissions
  4. Files as units
  5. Examining file contents
  6. Other commands
  7. Standard Files and Data Pipes

Redirecting input is not common, because most programs that read from standard input can also take filenames to read as arguments.

  • One example of input redirection uses the standard Unix mail program. When you use it to send mail, it normally reads the message text from the standard input (typed directly at the terminal). You can tell it to get the text from an already existing file with input redirection, for example,

    mail joe < messagetext

  • Another common use for input redirection is for simple fortran programs that you might write to analyze data files. Instead of hard-coding the filename of the input file into the program, which requires recompilation if you want to use a different input file, simply use read statements that read from the standard input (fortran unit 5). Then, when you run the program, you can redirect the standard input to any file you like, for example,

    myprog < myfile

Many commands and programs write output to the standard output, which defaults to the terminal. Often, you might want to save that output to a file instead for further study or processing.

  • For example, the ls -l command for a directory with many files creates many lines of output that can scroll rapidly up the screen. Save the output into a file to study with

    ls -l > listingfile

  • The cat program gives a good example of redirecting output. Instead of writing the file contents to the screen (its standard output) you can use cat to copy the contents into another file. This is often used to concatenate several files together, like:

          cat file1 file2 > file3

  • Use cat to add a line or two to a file without using the editor. Like most programs that work with files, if no input filenames are specified, cat reads from the "standard input", which is the terminal by default. Use this feature in combination with redirected standard output to append (add lines) to a file, like this:

    cat >> newfile

    After this command, you type in the new lines to be added to the file, and then end the input with a CTRL-D keystroke. For example, this is a handy way to add your printer specification to your .cshrc file. Just type these three lines to do it:

    cat >> .cshrc
    setenv PRINTER queue_name
    CTRL-D

    Use the desired printer queue name in place of queue_name. Don't forget that when you see CTRL-D written, it means to hold the CONTROL key down like a shift key and press the D key at the same time.

<--Previous Overview Next-->

Comments or Questions?