Strovent SystemsSign in
Reference

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=auto sends color codes only when standard output is connected to a terminal. Through a pipe it sends none. Use ls --color=always.
  • grep --color=auto behaves the same way. Use grep --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

Sources

Spotted a mistake? Email [email protected].