3

I have a function test1 which produces output on both stdout and stderr:

test1() {
    echo "out 1"
    sleep 0.1
echo "error 1" 1>&2
sleep 0.1

echo "out 2"
sleep 0.1

echo "error 2" 1>&2
sleep 0.1

}

I then have two aliases which format stdin and send it to stdout:

alias o='sed -E "s/^/O /"'
alias e='sed -E "s/^/E /"'

How can I pipe the two streams from test1 through o and e and end up with formatted output on stdout and stderr? I'm using Bash on Alpine Linux, so GNU utilities are not an option.

My reasoning goes as follows, but I don't know how to execute it syntactically:

  1. Send err to out and out to 3.
  2. Run in through e, send to err and 3 to out.
  3. Run in through o.
  4. Profit?
  • test1 > >(o) 2> >(e >&2)? – muru Jun 22 '20 at 07:16
  • @muru Sure but this leaves the process hanging and it's also out of order. – Tony Bogdanov Jun 22 '20 at 07:17
  • 1
    Once you send the streams to some other process, any chance of order goes out the window. (And it doesn't leave anything hanging for me, at least with the example you gave) – muru Jun 22 '20 at 07:27
  • @muru Yeah, you are correct, it doesn't hang, just continues to produce output after I'm give back control over bash. Order is important for me though... I'm pretty sure pipes can do this nicely I just can't figure out the syntax. – Tony Bogdanov Jun 22 '20 at 07:32

1 Answers1

2

You can do this by using bash process-subsitution:

Note that you have to redirect it back to stderr in order to avoid it being picked up by the stdout pipe:

$ perl -E 'say {*STDOUT} "hi"; say {*STDERR} "bye"' \
        > >(sed s/^/out:/)                          \
       2> >(sed s/^/err:/ >&2)
andreoss
  • 98
  • 5
  • 17
  • It works. There is slight problem I can't figure out: put in script it gives syntax error near unelected token \>' and in second line > >(sed s/^/out:/) ' `. It persists if I put it in single line too. – tansy Jun 05 '21 at 13:25
  • @tansy Works for me. Are you using bash and not other type of shell? https://www.ideone.com/684tU0 – andreoss Jun 25 '21 at 00:26