Heath Borders
Heath Borders

Reputation: 32107

Pipe output through a bash or, double pipe, || expression?

I have a noisy command whose output I want to hide on success. However, in a failure case, that output might prove helpful for debugging, so I want to show it before printing my error message.

Currently, I do it this way:

OUTPUT=$( cmd1 2>&1 ) || {
  echo $OUTPUT
  echo cmd1 failed
  exit 1
}

Is it possible to pipe cmd1's output through the || (or, double-pipe) so I can avoid creating a variable for the output?

Upvotes: 0

Views: 4542

Answers (3)

user2719058
user2719058

Reputation: 2233

Joey Hess' moreutils has a command chronic(1) which does precisely what you want: it runs a command, eating its stdout and stderr, unless the command exits non-zero, in which case the output is passed through.

Upvotes: 1

clt60
clt60

Reputation: 63892

Try the:

OUT=$(command....) && OUT= || { echo $OUT; exit 1;}
  • the && executed when the result of the command is OK (exit 0)
  • and clearing the OUT

Upvotes: 1

rici
rici

Reputation: 241671

You need to save the output of the command somewhere because you don't know until the command finishes whether or not to send the output to the console. Piping the output to something won't help, since pipes don't have large buffers.

You have a few options for buffering, but using a variable is a reasonable one if you don't expect megabytes of output, which would go well beyond the definition of noisy. You could also use a temporary file, but there are few advantages to that unless you're intending to deploy on a system with very limited memory (by today's standards).

Upvotes: 1

Related Questions