Reputation: 16441
I'm running a command that always prints some output. I want to see the output only if the command fails.
Something like this:
% (echo OK; true) | FILTER
% (echo ERROR; false) | FILTER
ERROR
Can FILTER
be implemented using standard shell tools?
The structure isn't necessarily a pipe. Something like FILTER "my_command"
is OK.
P.S. The actual program is a unit test, implemented using the Google Test suite. It's always quite verbose, and in case of success the output isn't interesting.
Upvotes: 2
Views: 2248
Reputation: 85550
You DONT need a sub-shell in your case, as you can see below, the exit code of a command set ( a list of commands separated by ';'), is the exit code of last command in the set. So only
true
orfalse
at the end matters in your examples. None of the commands before matter.
The best way to do this would be to use a command-substitution($()
), capture the output to a variable and use the shell built-in ||
operator, that runs the subsequent command only if the return code of the previous command is a failure.
var=$(echo ERROR); false || printf "%s\n" "$var"
ERROR
var=$(echo ERROR); true || printf "%s\n" "$var"
The inverse of the above clause would be
var=$(echo ERROR); true && printf "%s\n" "$var"
ERROR
var=$(echo ERROR); false && printf "%s\n" "$var"
See what the man
page has to say about for COMMAND LISTS
AND and OR lists are sequences of one of more pipelines separated by the
&&
and||
control operators, respectively.AND
andOR
lists are executed with left associativity. An AND list has the formcommand1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero. An OR list has the form
command1 || command2
command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.
Upvotes: 3
Reputation: 889
You could redirect stdout to /dev/null with this:
command 1>/dev/null
This way, only error messages appear.
Upvotes: 3