在管道到 T 恤时保留颜色

Paw*_*cki 87 pipe tee

ls -l --color=auto | tee output.log
Run Code Online (Sandbox Code Playgroud)

没有管道/三通,它是彩色的。我怎样才能使它在使用时保持着色tee(只能在屏幕上着色,我不关心日志中的颜色)。

Eam*_*ain 121

只需unbuffer在任何命令之前插入,使其认为它正在写入交互式输出,即使它实际上是通过管道传输到另一个可执行文件中。在 的情况下,这将保留颜色ls

例如

unbuffer ls -l --color=auto | tee output.log
Run Code Online (Sandbox Code Playgroud)

如果你还没有安装它,你可以在 Ubuntu 和其他 Debian-ish Linux 发行版上安装unbuffer它。

sudo apt-get install expect-dev
Run Code Online (Sandbox Code Playgroud)

  • 另一个不需要安装任何东西的解决方案是在 http://stackoverflow.com/questions/3515208/can-colorized-output-be-captured-via-shell-redirect (9认同)
  • 这会导致生成的文件包含颜色代码(当然);有没有办法以一种使用颜色代码并在终端中正确显示颜色的方式*打印*文件? (5认同)
  • 你不需要 `expect-dev` 包。`期望`就足够了。 (4认同)
  • 呃,这使得密码条目以明文形式显示您的密码! (3认同)
  • @Tgr 这个解决方案对我在 OS X 上尝试获取 `xcodebuild` 的原始彩色输出不起作用 - 相反,我得到了没有颜色的切碎的线条。 `取消缓冲 xcodebuild |然而 less -R` 工作完美。 (2认同)

Red*_*ick 15

使用 ls 选项 --color=always

--color=auto 不会彩色输出到管道 - 原因很明显。

主页上写着:

使用 --color=auto,仅当标准输出连接到终端 (tty) 时才会输出颜色代码。

  • @PawełGościcki 这个答案只解决了`ls` 的问题。请参阅我的答案,该答案解决了所有程序的问题,包括 heroku 日志。 (3认同)
  • 好的。这就解释了。但是我还能以某种方式看到屏幕上的颜色吗?(毕竟这是一个 TTY)。我不介意不在日志文件中包含它们,但我肯定希望它们出现在我的屏幕上。 (2认同)
  • grep 也有这个选项 (2认同)

Juu*_*nen 10

我将扩展script已接受答案的评论中给出的解决方案。script如果您不能或不想安装包含该命令的expect包,则使用可能会很有用unbuffer

使用颜色代码ls将输出打印到标准输出和文件:

script -efq output.log -c "ls -l --color=auto"
Run Code Online (Sandbox Code Playgroud)

其中 ( man script):

  -e, --return
         Return the exit code of the child process.  Uses the same
         format as bash termination on signal termination exit code is 128+n.
  -f, --flush
         Flush output after each write.  This is nice for telecooperation:
        one person does `mkfifo foo; script -f foo', and another can 
        supervise real-time what is being done using `cat foo'.
  -q, --quiet
         Be quiet (do not write start and done messages to either 
         standard output or the typescript file).
Run Code Online (Sandbox Code Playgroud)

查看带有颜色的输出文件:

less -r output.log
Run Code Online (Sandbox Code Playgroud)

  • `-e` 与 `--return` 相同 - 两者都不需要;`-efq` 是 `--return --flush --quiet`。 (2认同)