APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed


2003/12/29 2>&1


© Tony Lawrence, aplawrence.com

Shell redirection, and the "2>&1" is probably the most common form. That simply means to send stderr to wherever stdout is pointing. An easy way to demonstrate all this is to create a direcory and put one file in it:


mkdir tt
cd tt
touch t
 

That gives us a known situation to work with. Sitting in that directory,

ls foo t > y
 

Puts "t" in "y", but displays "ls: foo: No such file or directory" on the screen. That's because ls writes what it doesn't understand to stderr (file descriptor 2). If we want both things in y, we just do:

 ls foo t >y  2>&1 
 

Or, if you wanted the error output in a file as you might with "cc", for example:

cc source.c 2>/tmp/errors
 

There are lots of ways to do this sort of thing. More interesting is the case of a shell script where you want to capture stderr but let any "ok" output go to the screen. To do that, take advantage of other file descriptors:

x=`ls foo t 3>&2 2>&1 1>&3`
 

$x will have the error message but "t" will go to the screen. How does that happen? Well, 3>&2 puts stderr into (normally unused) file descriptor 3. Then 2>&1 puts 1 into 2. This might be hard for you to follow, but hang in there a minute. Next, 1>&3 puts 3 (which is the original 2) into 1. Effectively, this reverses stdout and stderr. Let's take a closer look:

When the shell starts , both stderr (1) and stdout (1) point to our screen. However, the

x=`ls foo t `
 

Would leave stderr still at the screen, but stdout would redirect to our "x" variable. We want the opposite of that: The 3>&2 makes 3 the same as 2, so now 3 is going to the screen. 2>&1 makes 2 go where 1 was, which is into our "x". Finally, 1>&3 puts 1 back to the screen by copying 3.

(See exec also)





2 comments




More Articles by

Find me on Google+

Tony Lawrence



"Shell redirection, and the "2&>1" is probably the most common form."

Er, you meant 2>&1, right?

--BigDumbDinosaur


Ayup :-)

--TonyLawrence


------------------------
Kerio Samepage


Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us















This post tagged: