Is there any way to keep colorization of text passed through pipe | to head, tail, less, etc.?
- 162,382
- 634
- 1
- 5
- 8
4 Answers
I presume you are piping from ls and want to preserve the terminal color codes. You can say ls --color=always (instead of the default of --color=auto), which will preserve the codes, but that won't guarantee that the thing you're piping to knows how to understand them.
If you use glark instead of grep it will try to display with colors.
If you use less with -R it will attempt to display with colors.
- 1,107
It depends on the program that generate the output in the pipe.
head, tail, etc aren't the ones removing the colors, it's the program generating the data that usually check if the output is going to the console (colored), a file or pipe (not colored)
I found another SU Q&A showing how to lie to piping programs to output as if they were sending output to a console (emulating a console with unbuffer)
- 406
On Mac OS X man ls mentions the CLICOLOR_FORCE environment variable.
Adding export CLICOLOR_FORCE=1 to ~/.zshrc or ~/.bashrc, depending on the shell you use, keeps the colors when piping ls to other commands like less, head, and tail.
- 11
Consider
bat
An alternative to
cat
Install
brew install bat
--args --flags like
--language and --theme
Examples
head | bat --language=zsh -n -p --theme=gruvbox-dark
file.py | bat --language=py -n -p --theme=gruvbox-dark
- 459