How to store standard error in a variable

It would be neater to capture the error file thus:

ERROR=$(</tmp/Error)

The shell recognizes this and doesn’t have to run ‘cat‘ to get the data.

The bigger question is hard. I don’t think there’s an easy way to do it. You’d have to build the entire pipeline into the sub-shell, eventually sending its final standard output to a file, so that you can redirect the errors to standard output.

ERROR=$( { ./useless.sh | sed s/Output/Useless/ > outfile; } 2>&1 )

Note that the semi-colon is needed (in classic shells – Bourne, Korn – for sure; probably in Bash too). The ‘{}‘ does I/O redirection over the enclosed commands. As written, it would capture errors from sed too.

WARNING: Formally untested code – use at own risk.

Leave a Comment