I have defined the following shell functions:
success() {
printf "[\033[32mSUCCESS\033[0m]\n"
}
failure() {
printf "[\033[31mFAILURE\033[0m]\n"
}
try() {
result=$($* 2>&1)
if [ $? -ne 0 ]; then
failure
echo $result
exit 1
fi
success
}
This allows me to silently execute any command, capturing all the output, and display a SUCCESS
or FAILURE
message. Only if the command fails, the command output is displayed for debugging:
try rm -r $tmp
But I just realized that it's limited to a single command, and fails miserably for a command piped to another with |
:
try git archive --format=tar HEAD | tar xf - -C $tmp
Because try
is executed only on the git
command, and then the output of try
is piped to tar
, instead of the output of git
.
Is it possible to pass the two commands git ... | tar ...
as a single parameter to try
, capturing the output of both, and check if both git
and tar
returned 0
?
Any other consideration maybe, to achieve my goal?
try git archive --format=tar HEAD \| tar xf - -C $tmp
? Though you almost definitely don't want the output of the first - if you caught it the second would have nothing to do. Still, if you mean diagnostic messages you'll want to change your command slightly like:$({ $* ; } 2>&1)
. You might also consider switching the$*
to"$@"
which should be more robust. – mikeserv Sep 12 '14 at 14:46