Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can colorized output be captured via shell redirect? [duplicate]

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?

like image 588
billc Avatar asked Aug 18 '10 18:08

billc


People also ask

Can colorized output be captured via shell redirect?

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.

How does redirection work in Shell?

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection allows commands' file handles to be duplicated, opened, closed, made to refer to different files, and can change the files the command reads from and writes to.

How do I copy a stdout to a file?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!


2 Answers

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).

like image 69
ataylor Avatar answered Oct 04 '22 22:10

ataylor


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.

like image 34
Walter Mundt Avatar answered Oct 04 '22 22:10

Walter Mundt