Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'How to capture output from certain Unix commands' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
How to capture output from certain Unix commands
Authored by: mjb on May 01, '08 02:25:52PM
In case anyone's interested, the string 2>&1 isn't just gibberish.. the numbers (1 and 2) are representative of the file handle ids for STDOUT (1) and STDERR (2). The > is for redirection, and the & is an 'escape'.

So, the outcome is "2 is redirected to 1, where 1 is a file handle, not a file". That's where the 'escape' comes in - it tells the shell that you want to redirect to a file handle, not a real file called "1". Basically STDERR is merged into STDOUT, so that any piping (|) or redirection (>) contains STDERR output too:

/path/to/somecommand -args > /tmp/output.txt 2>&1
(The redirection of STDERR to STDOUT and STDOUT to a file can be in either order, they're parsed by your shell then acted on simultaneously)

Note that due to buffering of the different data streams, the output can end up being 'out of sync' with each other, although this is rare.

[ Reply to This | # ]

How to capture output from certain Unix commands
Authored by: mjb on May 01, '08 02:31:59PM
Whoops, I lie. the order of redirections do indeed act in a different way, but the outcome is the same (and while I'm at it, the '&' isn't really an escape, just a convenient way of describing it).

For more information, have a look at the bash manpage (run 'man bash' in Terminal.app), and look at the section on Redirection (to skip to it, enter the following string in the man page reader: /^REDIRECTION and press enter.

[ Reply to This | # ]