1

I have the following two bash scripts:

one.bash:

#!/bin/bash

echo "I don't control this line of output to stdout"

echo "I don't control this line of output to stderr" >&2

echo "I do control this line of output to fd 5" >&5

callone.bash:

#!/bin/bash

# here I try to merge stdout and stderr into stderr.
# then direct fd5 into stdout.

bash ./one.bash 1>&2 5>&1

When I run it like this: bash callone.bash 2>stderr.txt >stdout.txt

The stderr.txt file looks like this:

I don't control this line of output to stdout
I don't control this line of output to stderr
I do control this line of output to fd 5

and stdout is empty.

I would like the "do control" line to be output to only stdout.txt.

The restrictions on making changes are:

  1. I can change anything in callone.bash.
  2. I can change the line in one.bash that I control.
  3. I can add an exec in one.bash related to file descriptor 5.
  4. I have to run the script as indicated.

[EDIT] The use case for this is: I have a script that does all kinds of running of other scripts that can output to stderr and stdout. But I need to ensure that the user only sees the well controlled message. So I send the well controlled message to fd5, and everything else (stdout & stderr) is sent to the log.

Be Kind To New Users
  • 9,672
  • 13
  • 78
  • 125

1 Answers1

7

Redirections happen in order.

Once you run 1>&2 you've replaced fd 1 with fd 2.

So when you then run 5>&1 you are redirecting fd 5 to where fd 1 points now (not where it was when it started).

You need to invert the two redirections:

bash ./one.bash 5>&1 1>&2
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • The fun thing is that when pipes get involved, it is *not* the same. – o11c Jul 10 '15 at 23:09
  • @o11c, the pipe is set up first, then the redirections. See http://stackoverflow.com/a/12027221/1524545 – geirha Jul 10 '15 at 23:41
  • @o11c What's not the same? – Etan Reisner Jul 10 '15 at 23:45
  • @EtanReisner the pipe is on the right, but happens first. – o11c Jul 10 '15 at 23:50
  • Ah, I see. That's still in order, just not the order you might naively expect. It makes sense when you understand how the pieces have to work together. Anything else would be impossible to use correctly (unable to redirect using to/with the pipe correctly). – Etan Reisner Jul 12 '15 at 12:58