Posted by: kuanhoong | 19/04/2009

Using redirections: 2>&1 (Part 2 of 2)

If you go through enough shell scripts, you will notice the frequent use of 2>&1.  What does it mean and how it works?

We have briefly introduced standard in (stdin) and standard out (stdout).  In the command line interface and also in shell programming, these are represented as follows:

  • 0 Standard In (STDIN)
  • 1 Standard Out (STDOUT)
  • 2 Standard Error (STDERR)

The 2>&1 basically means that to redirect standard error (STDERR) to standard out (STDOUT).  We use tar to archive the home directory of the user susetips and redirect the verbose output to a file bak.log as an example;

# tar cvf susetips.bak /home/susetips >> bak.log
tar: Removing leading ‘/’ from member names

The command above basically kept a listing of the files that were backed up in the file bak.log.  This file can be kept as a reference to know what files were actually backed up.  However, there’s a message from the tar command that still appeared on the terminal.  This message is a warning/error message that outputs to STDERR, which in this case is the terminal.  The >> redirection just puts the STDOUT to the file but not the STDERR.  To redirect the STDERR to the same place as the STDOUT;

# tar cvf susetips.bak /home/susetips >> bak.log 2>&1
#

Where the 2 represented STDERR, > means redirect to and &1 is the variable name for STDOUT.  You can check the content of the file bak.log by using the cat command.


Leave a comment

Categories