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
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)
Enter your email address for automatic notification of new posts here
(be sure to whitelist 'feedburner.com' if you use spam filtering)
| Views for this page | ||||
|---|---|---|---|---|
| Today | This Week | This Month | This Year | Overall |
| 10 | 10 | 108 | 3,681 | 14,779 |
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. We appreciate comments and article submissions.
Add your comments
Installation and light training Boston and New England