Wednesday, August 1, 2007

Standard Input and Output in Linux

Every process in Linux has 3 connections to the outside world.  They are:

  • Standard Input (stdin): default to the keyboard
  • Standard Output (stdout): default to the monitor screen
  • Standard Error (stderr): default to the monitor's screen
In Unix/Linux each of these connections is also associated with a file descriptor:
  • 0: stdin
  • 1: stdout
  • 2: stderr
To redirect a process's output to a file (only normal messages, no errors):
Standard input can also be represented by '-'.
This is equivalent to copy con outputfile in DOS.
$ command > outputfile 
$ command - > outputfile

To direct a file as standard input: 
command < inputfile

To direct standard input to a file:
cat  > outputfile

To direct a process's output to another process (command) as standard input, use pipe:
command_out | command_in
e.g. cat filename | more

To direct error to a file:
   $ command 2>errors.txt  # 2 indicates the error stream in Linux
   $ command 2>/dev/null   # /dev/null is a device where anything you send simply disappears.

To direct both standard output and error to a file:
   $ command > error.log 2>&1  # '&1' represent stdout.
To direct stdout to output.log and stderr to error.log, and print only error to the screen:
   $ command 2>&1 > output.log | tee error.log

   # append error to the same output.log file instead of error.log.
   $ command 2>&1 > output.log | tee -a output.log

No comments:

Post a Comment