3

I've seen a zillion permutations on this question but I think none is an exact duplicate.

Can I copy only stderr (or eventually stderr and stdin) to a file, while keeping the colorized output on the screen (if the files are colorized also, that's a bonus)

0

2 Answers 2

2

Each command can have an a special command to always send color escape code as show in other answers. But a more generic approach is to use to following tools.

unbuffer

unbuffer ls -l --color=auto | tee output.log

unbuffer is a command from the expect package.

Ref. SuperUser - reserve colors while piping to tee

script

script --flush --quiet --command "ls -l --color=auto" | tee output.log

script is a command from the util-linux package.

Ref. StackOverflow - Can colorized output be captured via shell redirect? [duplicate]

0
0

A pipe or redirection won't remove any colors!


The initial command that you're using removes the colors when it notices that the output is not a terminal! So cannot be a general answer to that question.

See e.g. man ls:

ls emits color codes only when standard output is connected to a terminal.

You can change the behavior using --color=always.

Same for grep:

   --color[=WHEN], --colour[=WHEN]
          Surround  the  matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields
          and groups of context lines) with escape sequences to display them in color on the terminal.  The  colors  are  defined  by  the  environment
          variable  GREP_COLORS.   The  deprecated environment variable GREP_COLOR is still supported, but its setting does not have priority.  WHEN is
          never, always, or auto.

For example:

echo 123 | grep --color=always 2 | tee file

... will have the 2 colored for the output in the terminal and also in the file.

To have the colors in the output, but not in the file, you can check answers to this question and then run e.g. this:

echo 123 | grep --color=always 2 | tee /dev/tty | ansi2txt > file

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.