bash command preserve color when piping [duplicate]

不问归期 提交于 2019-11-28 20:12:32

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"
Foo Bah

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!