less shows ESC[31m instead of colors: less -R and --color=always
Colored output piped into less shows ESC[31m and ESC[0m because less prints control characters as text. Use less -R, and make the program keep its colors.
You pipe colored output into less and get this instead of colors:
ESC[01;31mERRORESC[0m disk full
Nothing is broken. The program sent color escape sequences, and less is showing them as text.
Why less shows ESC
By default less displays control characters in caret notation, for example Ctrl+A as ^A, so that it always knows what is on the screen. The escape character that starts every color sequence is shown as ESC, and the rest of the sequence ([01;31m) as ordinary text.
Show the colors: less -R
grep --color=always error app.log | less -R
-R (--RAW-CONTROL-CHARS) passes ANSI color sequences, and OSC 8 hyperlinks, through to the terminal as they are, and still keeps track of the screen layout. The manual notes that a color is expected to change within a line: each new line is assumed to start in the normal color.
-r passes all control characters through. That can scramble the display, because less no longer knows where the cursor is. Prefer -R.
To use -R every time, set the LESS environment variable in your shell's startup file:
export LESS=-R
Options in LESS are read before the command line, so less -+R turns it off again for one run.
No colors at all in less
If less -R shows plain text, the program did not send colors in the first place. Many programs color their output only when it goes straight to a terminal:
ls --color=autosends color codes only when standard output is connected to a terminal. Through a pipe it sends none. Usels --color=always.grep --color=autobehaves the same way. Usegrep --color=always.
Other programs have their own switch, often --color=always or an environment variable. Check the program's manual.
When the codes show up somewhere else
- If the codes show in a file, the program wrote them there with
always. View the file withless -R, or strip the codes by running the program again with--color=never. - If the codes show everywhere, not only in
less, the terminal type may be wrong: see Do all terminals understand ANSI escape codes? TERM, terminfo and dumb terminals.
Related
- Colors: 16, 256 and true color
- Escape sequences
- Do all terminals understand ANSI escape codes? TERM, terminfo and dumb terminals
- Print escape sequences with echo -e or printf: why it differs between shells