Georgi Georgiev
Georgi Georgiev

Reputation: 1623

Redirecting stderr

There is something that bothers me a lot. I want to redirect stderr to lets say fd 5. So I run the following command:

me@/home/me>$ exec &2>5

[1]     307

So what I expect as result of this redirection is, that from now errors will be send to fd 5. But this is what happens:

me@/home/me>$ mkdir /a 5>/dev/null
mkdir: /a: [Permission denied]

It sill shows the error on stdout. While when I redirect 2 it shows nothing:

me@/home/me>$ mkdir /a 2>/dev/null

Can someone please explain where am I wrong?

Upvotes: 1

Views: 304

Answers (1)

Jay
Jay

Reputation: 9656

exec &2>5

This does not redirect stderr to file descriptor 5. It redirects it to a file named 5. Note that as glenn jackman mentioned in a comment, this is done in the subshell created by backgrounding exec only (the & that you used does not mean that 2 will be treated as a file descriptor. It means exec will be called in the background!

mkdir /a 5>/dev/null

This redirected file descriptor 5 to /dev/null.

You can redirect stderr to a file like this:

mkdir /a 2>some-file

Now look at the difference between these:

mkdir /a 2>&1          # redirect stderr to fd 1, which is stdout
mkdir /a 2>1           # redirect stderr to file named "1"
mkdir /a >x 2>&1       # redirect stdout to x, AND stderr to stdout, which also goes into x
mkdir /a 2>&5          # redirect stderr to fd 5, presuming there IS an open file with fd 5

Upvotes: 1

Related Questions