开发者

bash command preserve color when piping [duplicate]

开发者 https://www.devze.com 2023-04-10 03:24 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Can colorized output be captured via shell redirect?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Can colorized output be captured via shell redirect?

setup

In this case specifically I'm trying to preserve the colors in git status -s w开发者_开发问答hen piping it to another command.

Some git commands, diff for instance, and other commands like grep have an option --color=always but git status does not.

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?


Here's a script snippet using the colorized output of ls as an example (on 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"


Most commands that do print out those color codes explicitly check if stdout/stderr is a tty (using the isatty function).

If you want to preserve the color codes, you can run it within a terminal emulator like screen or the direct logger script, saving the output to a file.

0

精彩评论

暂无评论...
验证码 换一张
取 消