Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Is it possible to capture stdout and stderr to separate variables in Zsh?



On Tue, 2012-03-06 at 09:09 +0100, Nikolai Weibull wrote:
> Is it possible to capture stdout and stderr to separate variables in Zsh?
> 
> I understand that it’s not possible in sh, but I was wondering if any
> of Zsh’s additions in the redirection area would allow for such a
> separation.

All I can think of is:

        coproc cat &
        pid=$!
        stdout="$( ( print "printed on stdout"; print -u 2 "printer on stderr" ) 2>&p )"
        sleep 1 
        kill "$pid"
        stderr="$(cat <&p)"
        print "stdout=\"$stdout\""
        print "stderr=\"$stderr\""

You'll notice the very ugly sleep+kill hack I had to use as I could not
find how you can close a coprocess's standard input cleanly.  Removing
the sleep+kill makes the cat <&p hang forever.

Of course this solution will hang if more than a buffer-full is printed
on stderr.  You can play tricks with dd by providing a bigger buffer, as
in:

        coproc dd obs=1M &

But in the end it's a losing game.  You might as well use a temporary
file for one of the output streams.

A completely different solution could involve the tcp zsh module which
can multiplex many streams with tcp_expect.  But that's probably too
involved for this problem.

Phil.



Messages sorted by: Reverse Date, Date, Thread, Author