流式命令替换输出到终端 w/o 压制颜色

Streaming command substitution output to terminal w/o squelching color

有没有办法在命令替换执行时以颜色显示命令替换的输出,同时仍将其存储到变量中?这主要是为了testing/debugging目的,输出不会正常显示。

如果我这样做:

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

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

如何有条件地将输出流式传输到终端而不抑制颜色?

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

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)