views:

40

answers:

3

Various bash commands I use -- fancy diffs, build scripts, etc, produce lots of color output.

When I redirect this output to a file, and then cat or less the file later, the colorization is gone -- presumably b/c the act of redirecting the output stripped out the color codes that tell the terminal to change colors.

Is there a way to capture colorized output, including the colorization?

+1  A: 

One way to capture colorized output is with the script command. Running script will start a bash session where all of the raw output is captured to a file (named typescript by default).

ataylor
A: 

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.

Walter Mundt
`ls --color` is the same as `ls --color=always` - you're thinking of `ls --color=auto`
Dennis Williamson
Good catch; edited to fix.
Walter Mundt
+1  A: 

some programs remove colorization when they realize the output is not a TTY (i.e. when you redirect them into another program). You can tell some of those to use color forcefully, and tell the pager to turn on colorization, for example use less -R

alvherre
Thanks guys. This is good info and clarifies a lot what is actually happening. I forgot about the script command... it does exactly what I need!
billc