流命令替换输出到终端w / o静噪颜色

时间:2015-11-17 15:26:40

标签: bash command-substitution

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

如果我这样做:

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

...然后这很接近,但不是我想要的几个方面:

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

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

1 个答案:

答案 0 :(得分: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)