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

Re: capture stderr in command substitution



2021-01-25 12:38:00 +0000, Stephane Chazelas:
> 2021-01-24 11:45:31 -0800, Ray Andrews:
> > $ var=$(command)
> > 
> > ... but $var doesn't pick up errors.  Can it be forced?
> [...]
> 
> var=$(cmd>&2)
> 
> like in any Korn/POSIX-like shell.
[...]

D'oh sorry, that should be cmd 2>&1 (redirect fd 2 to the same
resource as fd 1 is redirected to (the writing end of the pipe
the other end of which is read by the shell to fillup $var)),
not cmd >&2 which would redirect stdout to the same resource as
fd 1 is redirected to, leaving none of cmd's file descriptor
connected to that pipe.

> To capture only stdout:
> 
> { var=$(cmd 2>&1 >&3 3>&-); } 3>&1
> 
> That is we need to redirect cmd's stdout back to what it was
> originally (after having redirected cmd's stderr to the pipe),
> using that extra fd 3 temporarily.
> 
> That's also standard sh syntax.
[...]

That one is correct.

-- 
Stephane




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