bash 命令在管道时保留颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7641392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash command preserve color when piping
提问by rennat
Possible Duplicate:
Can colorized output be captured via shell redirect?
可能的重复:
可以通过 shell 重定向捕获彩色输出吗?
setup
设置
In this case specifically I'm trying to preserve the colors in git status -swhen piping it to another command.
在这种情况下,特别是在将颜色通过git status -s管道传输到另一个命令时,我试图保留其中的颜色。
Some git commands, difffor instance, and other commands like grephave an option --color=alwaysbut git statusdoes not.
diff例如,一些 git 命令和其他类似的命令grep有一个选项--color=always但git status没有。
question
题
Is there a way to pipe or capture the output of a command and make it think it is outputting to the xterm shell so it doesn't automatically disable colors?
有没有办法通过管道或捕获命令的输出并使其认为它正在输出到 xterm shell,因此它不会自动禁用颜色?
采纳答案by vego
Here's a scriptsnippet using the colorized output of lsas an example (on Mac OS X 10.6).
这是一个script使用彩色输出ls作为示例的片段(在 Mac OS X 10.6 上)。
# no colored ls output if stdout is a pipe (and not a tty)
ls -G /
ls -G / | cat
script -q /dev/null ls -G / | tr -d '\r' | cat
# write output of script command to a variable
var="$(script -q /dev/null ls -G / | tr -d '\r' | cat)"
echo "$var"
回答by Foo Bah
Most commands that do print out those color codes explicitly check if stdout/stderr is a tty (using the isattyfunction).
大多数打印出这些颜色代码的命令都会明确检查 stdout/stderr 是否是 tty(使用该isatty函数)。
If you want to preserve the color codes, you can run it within a terminal emulator like screenor the direct logger script, saving the output to a file.
如果您想保留颜色代码,您可以在终端仿真器中运行它,例如screen或直接记录器script,将输出保存到文件中。

