Can colorized output be captured via shell redirect? [duplicate]
Redirecting doesn't strip colors, but many commands will detect when they are sending output to a terminal, and will not produce colors by default if not. For example, on Linux ls --color=auto
(which is aliased to plain ls
in a lot of places) will not produce color codes if outputting to a pipe or file, but ls --color
will. Many other tools have similar override flags to get them to save colorized output to a file, but it's all specific to the individual tool.
Even once you have the color codes in a file, to see them you need to use a tool that leaves them intact. less
has a -r
flag to show file data in "raw" mode; this displays color codes. edit: Slightly newer versions also have a -R flag which is specifically aware of color codes and displays them properly, with better support for things like line wrapping/trimming than raw mode because less can tell which things are control codes and which are actually characters going to the screen.
Inspired by the other answers, I started using script
. I had to use -c
to get it working though. All other answers, including tee
, different script
examples did not work for me.
Context:
- Ubuntu 16.04
- running behavior tests with
behave
and starting shell command during the test with python'ssubprocess.check_call()
Solution:
script --flush --quiet --return /tmp/ansible-output.txt --command "my-ansible-command"
Explanation for the switches:
--flush
was needed, because otherwise the output is not well live-observable, coming in big chunks--quiet
supresses the own output of the script tool-c, --command
directly provides the command to execute, piping from my command to script did not work for me (no colors)--return
to make script propagate the exit code of my command so I know if my command has failed