On 2012-06-08, Ben Bacarisse <
ben.u...@bsb.me.uk> wrote:
> I have a bash script that captures the output of a command (it's gpg, as
> it happens) and also tests the exit code:
>
> out=$(command 2>/dev/null)
> [[ $? -eq 0 ]] || exit 1
More simply:
out=$(command ...) || exit 1
A variable assignment acts as a command, with a termination status
that can be tested in the normal way.
> In order to improve the error messages from the script, I'd now like to
> distinguish between two error cases, but the command exists with the
> same $? in both. The error output, however, *is* different.
Unfortunately there is no shell feature for capturing standard error and
standard output into different variables.
Moreover, fifo-based hacks to avoid creating a file run into the problem
that they require parallel subprocesses, which cannot set a variable
in the parent (other than via some print/eval hack: that may be something).
> In short, am I missing some trick that can simplify this:
>
> tmp=$(mktemp)
> out=$(command 2>$tmp)
> if [[ $? -ne 0 ]]; then
> # examine content of $tmp and report accordingly
> fi
> rm $tmp
The concern about what goes into the temp file could be addressed
using Bash's process substitution.
Perhaps process substitution, if the "examine content" part can be
confined to a subprocess:
if ! out=$(command ... 2> >(grep "whatever" > $tmp)) ; then
# process temp file contents.
fi
That is to say, we redirect stderr not directly to a file, but
to a pipeline which greps out some relevant part of the error
message and sends only *that* to a file.
Hopefully this will suppress something sensitive in the error
output that should not go into the file.