1

I want to redirect everything that is supposed to go to stdout to stderr, and everything that is going to stderr to go to stdout instead.

The following code does not work:

$ bin/stdout-test 1>&2 2>&1

I'm sure there is a practical use for this somewhere out there, but currently it's just a mental exercise to help learn and understand io redirection.

In Ubuntu, both stdout and stderr get redirected to the console anyway, so you can't really tell if you are making any progress, but the command tcpserver will redirect stdout to the connecting remote user, and stderr to the terminal that started the tcpserver session, making it a perfect place to test this type of redirection.

I created a test project just for this purpose:

IQAndreas
  • 8,060
  • 8
  • 39
  • 74

1 Answers1

7

Your attempt does not work because 1>&2 merges stdout into stderr, and after that there is no hope of ever separating them again. You need a third temporary file descriptor to do the swap, like when swapping the values of two variables.

Use exec to move file descriptors.

( exec 3>&1- 1>&2- 2>&3- ; bin/stdout-test )

or just

bin/stdout-test 3>&1- 1>&2- 2>&3-

Explanation:

  1. 3>&1- moves stdout (FD 1) to FD 3
  2. 1>&2- moves stderr (FD 2) to FD 1
  3. 2>&3- moves FD 3 to stderr (FD 2)

See Moving File Descriptors.

200_success
  • 7,286
  • 1
  • 43
  • 74