7

Is there a way in the Linux command line, to only have a command pipe its output to another, when the command didn't fail?

$ cmda | cmdb

I would like it, so when cmda returns a status code other than 0, its output doesn't get redirected to cmdb.

Jeroen
  • 767
  • 4
  • 12
  • 29

1 Answers1

8

You will need to store the output in a variable to accomplish this. Here is an example:

if output=$(cmda); then
  printf '%s' "$output" | cmdb
fi
jordanm
  • 41,988
  • 9
  • 116
  • 113
  • Does not seem to work for `command info put` – winklerrr Jul 02 '21 at 09:16
  • @winklerrr can you post an example? This works fine for me `if output=$(command info ls) ; then echo "successful because 'ls' exists" ; else echo failure; fi` – Chris Jun 19 '22 at 00:02