简体   繁体   中英

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?

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).

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

乔伊·赫斯(Joey Hess)的moreutils具有一个命令chronial chronic(1) ,它可以精确地执行您想要的操作:它运行一条命令,吃掉它的stdoutstderr除非该命令退出非零值, 否则输出将通过。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM