Shell – Replacing stdout with stderr

file-descriptorsio-redirectionshell

Is it possible to redirect the output from a command to replace the text sent to stdout with the text from stderr?

$ ./script
this line is redirected to stdout
this line is redirected to stderr

$ ./script (insert redirections here)
this line is redirected to stderr

I know I could just use 1>/dev/null, but I want to know if there's a way to do this with the text from stderr redirected to stdout.

Best Answer

You can do it like this:

./script 2>&1 1>/dev/null

This redirects fd 2 to what fd 1 points to (i.e. stdout), then redirects fd 1 to /dev/null. The second redirect doesn't affect the first one, output to fd 2 will be sent to stdout.

Order does matter though. With this:

./script 1>/dev/null 2>&1

will send all output to /dev/null.

Related Question