Input/Output Redirection

Introduction

Most UNIX commands:

  • Read input from the standard input, stdin.
  • Write output to the standard output, stdout.
  • Write error messages to the standard error, stderr.

Notes

  • By default, stdin, stdout, and stderr are your terminal.
  • Your shell will let you run commands so that one or all those are files instead of the terminal.

stdin

  • To make a command read from a file instead of a terminal, use < filename on the command line.
  • To mail the content saved in a file called message:
    
    % mail kensmith < message
    
    

stdout

  • If you want to save the output of a command to a file, type the command as normal, including any arguments it needs, and end the command with filename where filenameis the name of the file you want the output saved in.
  • Some commands will check to see if stdout is a file instead of a terminal and will change the output format:
    
    % ls /usr/local > listing
    % cat listing
    bin
    etc
    games
    include
    lib
    lib64
    libexec
    sbin
    share
    src
    % ls /usr/local
    bin  etc  games  include  lib  lib64  libexec  sbin  share  src
    % 
    
    
  • Example: you can combine all files beginning with mail. into a single file called MAIL with:
    
    % cat mail.* > MAIL
    
    
  • If MAIL didn't exist before, it is created.
  • If MAIL did exist before, it is overwritten, and the previous contents of the file are gone.
  • You can set the shell variable noclobber to have shell give an error if MAIL exists instead of overwriting it
  • You can append to a file instead of overwriting it by using >> instead of > for output redirection.
  • Be careful when using wildcarding and I/O redirection!
  • Your shell creates the output file first, then does the wildcarding:
    
    % ls
    file.1  file.2
    % cat file.* > file.3
    cat: input/output files 'file.3' identical
    % 
    
    

stderr

  • If error messages should be saved in file too use >& for output redirection.