swap stderr and stdout

swap stderr and stdout

Post by John Smit » Thu, 26 Jul 2001 07:35:07

I am trying to swap stderr and stdout (filedescriptor 1 and 2). any ideas on
how to do it in shell??

swap stderr and stdout

Post by Alex Mitrofano » Thu, 26 Jul 2001 14:06:33

> HI..
> I am trying to swap stderr and stdout (filedescriptor 1 and 2). any ideas on
> how to do it in shell??
> thanks

One possible solution is to create backup copy for one of two descriptors.
For example:
- create backup copy of 1,
- redirect 2 to 1
- redirect copy of 1 to 2

command  7>&1 >&2 2>&7

Hope this helps,

Alex Mitrofanov
Brainbench MVP for Unix Programming


1. swapping stdout & stderr, OK?

In a particular process which forks 1 child, I would like to have the
parent log to stdout and the child to stderr both using functions which
typically write to stdout (like puts(), and printf()).
Then when I launch the program, I can use redirection to specify the files
to which I log, rather than adding parameters to the programs. Also, then,
if I run it interactively, both processes' output goes to my terminal.

Here's what I've done:

#include <my_environ.h>

#define STDOUT 1
#define STDERR 2

   int saved_fp;
   if ((saved_fp = dup(STDERR)) == -1) exit(1);
   if (dup(STDOUT) != STDERR) exit(1);
   if (dup(saved) != STDOUT) exit(1);

and... it works. Afterward, puts() goes to stderr, and fprintf(stderr,) goes
to stdout (from the shell's perspective anyway).

However, I'm wondering if it is legal to do this, ie. rely
on dup() to return the lowest fd after closing stdout, for instance. (I assumed
stdin fd was unavailable.) Is it OK to close stdout and stderr in this way?

Please email. Thanks,

2. VMware + 2.4.17

3. Redirecting stdout and stderr, and stderr

4. peripherals - touchpad and video drivers?

5. stderr & stdout to file and stderr to screen

6. Q: read one character from a stream ?

7. ksh redirect stdout & stderr > file1, stderr > file2

8. Logitech Mouse doesn't work..

9. file descriptor Q, redirecting stderr and stdout to stdout and file.

10. General stderr, stdout, /dev/null help

11. Redirect stdout and stderr in ksh

12. highlight stderr, leave stdout alone

13. Joining stdout & stderr of subprocess ?