0

有没有办法在执行时以颜色显示命令替换的输出,同时仍将其存储到变量中?这主要用于测试/调试目的,并且输出不会正常显示。

如果我这样做:

output=$(some_command)
if [ "$debug" ]; then
  echo "$output"
fi

...那么这很接近,但在某些方面不是我想要的:

  • 即使命令会以其他方式向终端发出彩色输出,它也会以黑白打印。
  • 输出仅在命令完成后显示,而不是在运行时流式传输。

如何在不压制颜色的情况下有条件地将输出流式传输到终端?

4

1 回答 1

6

要将命令的结果存储到变量并将其输出流式传输到控制台:

var=$(some_command | tee /dev/stderr)

如果您想强制您的命令认为它直接输出到 TTY,从而在不在管道中时启用颜色输出,请使用工具unbuffer,附带expect

var=$(unbuffer some_command | tee /dev/stderr)

综上所述:如果您只想有条件地显示长脚本的调试,则将条件放在脚本的顶部而不是将其分散在各处是有意义的。例如:

# put this once at the top of your script
set -o pipefail
if [[ $debug ]]; then
  exec 3>/dev/stderr
else
  exec 3>/dev/null
fi

# define a function that prepends unbuffer only if debugging is enabled
maybe_unbuffer() {
  if [[ $debug ]]; then
    unbuffer "$@"
  else
    "$@"
  fi
}

# if debugging is enabled, pipe through tee; otherwise, use cat
capture() {
  if [[ $debug ]]; then
    tee >(cat >&3)
  else
    cat
  fi
}

# ...and thereafter, when you want to hide a command's output unless debug is enabled:
some_command >&3

# ...or, to capture its output while still logging to stderr without squelching color...
var=$(maybe_unbuffer some_command | capture)
于 2015-11-17T15:58:30.133 回答