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 23:01 -0800, Bart Schaefer wrote:
> On Mar 6,  9:16am, Philippe Troin wrote:
> }
> } 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?
> } 
> } 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)"
> } 
> } 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.
> 
> You need this:  http://www.zsh.org/mla/users/2011/msg00095.html  :-)

I didn't see anything in there that could suppress the sleep+kill.

> } 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.
> 
> You might also be able to do something with the zsh/zselect module, but
> just use a temp file.  That solution works in bash, too.

I like Nikolai's solution best, except that it's somewhat cryptic and it
munges NULs and trailing newlines.

outs=("${(@0):-"$({ out=$(x) } 2>&1; print $'\0'$out$'\0'$status)"}")

Phil.



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