Catching errors in a shell scripts

Matthew Flaschen matthew.flaschen at gatech.edu
Sun Apr 8 01:30:32 UTC 2007


Simon Skogh wrote:
> I'm sure the subject line is a tad confusing, but I'm having problems
> coming up with a better description.
> 
> To cut to the chase, what I'm trying to achieve is executing a command
> from within a shell script and trap it in a variable. This works just
> fine using something like
> OUTPUT=`command`
> but it doesn't seem to grab any errors.

I see.  That's because standard output and standard error are different
streams, and `command` (incidentially I find the equivalent $(command)
easier to type) apparently doesn't capture standard error.  The below
works, but there may well be a less hackish way.  This is a demo for
capturing the error from trying to copy a non-existent file.  For all
commands, it will capture both error and output to alloutput:

tempoutput=`mktemp`
cp nonexistent_file backup &> tempoutput;
alloutput=`cat tempoutput`
rm $tempoutput;
echo "All output: $alloutput"

mktemp generates a random filename, which helps prevent shenanigans.

Matt Flaschen




More information about the ubuntu-users mailing list