Wednesday, July 2, 2008

Always confused with 2>&1

For those confused, I am talking about the stdout & stderr. And redirection operators.

This is more of the commands used in linux terminals.

Consider this command:
tar -cvf filename.tar

If you run this command it prints a lot on stdout (terminal). So if you want to redirect this output to /dev/null you would do that using:
tar -cvf filename.tar 1>/dev/null
(or better)
tar -cvf filename.tar.gz >/dev/null

If you are using tar in a script & want to capture/redirect the stdout of tar in a file, you can use:
tar -cvf filename.tar >tar_stdout.log
(here > symbol is used to redirect)

Now, if there is an error while tarring (say disk full). Then the command will print error on stderr & will exit. So how will you capture the errors, now you want to redirect both stderr & stdout to files.

There are to scenarios here:
1. You want to redirect to two seperate files:
tar -cvf filename.tar 1>tar_stdout.log 2>tar_stderr.log
2. You want to redirect stdout & stderr to a single file:
tar -cvf filename.tar >tar_stds.log 2>&1

Remember always: This applies to all commands:
The arguments are put to a variable (
ARGV) of that process, and this variable is accessed as a stack. In the previous example 2>&1 (instruction to the shell to redirect 2 to 1) should be at the end. So that this (2>&1) redirection is arranged first & then 1>tar_stds.log. Good example is:
mkdir dir1/dir2 dir1 --> Valid
mkdir dir1 dir1/dir2 --> Invalid

Redirection operators include:
> (output redirect)
< (input redirect) >> (output redirect but append)

The same redirect operators can be used to redirect I/O to other file numbers OR to files. The distinction is:
tar -cvf file.tar 1>stdout.log -> this acts as redirect to file
tar -cvf file.tar 1>&2 -> this acts as redirect to another file number(notice the &)

PS:-
I use bash

0 comments: