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

Re: capturing stderr to variable.



On Nov 14,  7:56am, Mikael Magnusson wrote:
}
} On Sat, Nov 14, 2015 at 5:18 AM, Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
} >
} > wondering, since redirection and piping are (I believe) at about the
} > same level of parsing, one might suppose that " ... 2| " would be
} > legal. That is to say that we could sent stderr to a command as well
} > as to a file.
} 
} foo 2> >(bar)

That doesn't really help very much, though, because >(bar) runs in a
separate process so the original shell can't do anything interesting
with the captured output.

The shell language doesn't define a digit preceding a "|" symbol as a
redirection because "|" separates commands whereas ">" modifies the
single current command.  The difference makes more sense if you are
aware that redirections can appear anywhere:

    % >file echo this goes to file
    % echo this >>file also goes to file

Whereas "|" ends the command and begins the next.

So, pipes work only on stdout, and to redirect stderr to a pipe you
must first use 2>&1 to copy stderr to stdout ... which means even if
you think it's unclear, you must first separately redirect stdout in
order to pipe only stderr.

E.g.
	{ highlight ... >/dev/tty } 2>&1 | read highlight_err
	# now $highlight_err has the first line of stderr
	# (this does not work in most shells other than zsh)

Note that without the braces, 2>&1 combines stdout and stderr so
both go to /dev/tty and "read" either has no input or reads from
the terminal (depending on whether the "multios" option is set).

-- 
Barton E. Schaefer



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