Using less -R to Preserve ANSI Color in Command Output
Shows how to use less -R to view ANSI-colored output, set defaults via LESS, and avoid pitfalls like garbled escape sequences or line truncation.
13 Jul 2025, 01:14 UTC

Using less -R to keep ANSI colors
When a command such as grep --color=auto pattern file or ls --color writes ANSI escape sequences to its stdout, the default less pager strips those sequences, leaving monochrome output. Adding the -R flag tells less to pass the escape sequences through to the terminal, so colors appear as they would in an interactive shell.
Worked example: setting a default LESS variable
Add the following line to your shell startup file (~/.bashrc or ~/.zshrc) to make less always interpret raw ANSI characters, chop long lines, and ignore case in searches:
export LESS='-R -S -i'
After reloading the shell (source ~/.bashrc), any invocation of less will inherit these options. For instance:
grep --color=auto 'root' /etc/passwd | less
Run the command in a terminal that supports ANSI colors (most modern terminals do). You should see the matching line highlighted in the same colors as when the pipe to less is omitted.
Limits and common mistakes
- If the terminal does not understand ANSI escape sequences (e.g., some very old hardware or certain logging viewers), the raw sequences will be displayed as gibberish, making the text unreadable. In that case, drop the
-Rflag or useless -ronly when you know the output contains only safe characters. - Feeding binary data to less with
-Rcan cause the pager to interpret random bytes as escape sequences, potentially scrambling the screen. Avoid piping raw binary files (e.g.,cat image.bin | less -R) unless you are certain the data contains no escape‑like bytes. - The
-Soption, often combined with-Rto keep tables aligned, truncates lines that exceed the viewport width. Information beyond the cutoff is lost unless you temporarily disable line chopping with the toggle-Swhile inside less (press-Sagain). Verify truncation by viewing a long line:printf '%0.sX' {1..200} | less -Sshould show exactly the number of X characters that fit in your window.
Practical verification
- Run a colored command and pipe to less:
ls --color=always . | less. If you exportedLESS='-R'earlier, colors should appear without extra flags. - Toggle the line‑chopping behavior: while inside less, press
-Sto turn chopping off and observe whether long lines now wrap or are displayed with a continuation marker. - To confirm that -R is truly passing escape sequences, run a command that sets a color via tput and pipe to less:
{ tput setaf 3; echo 'warning'; tput sgr0; } | less -R. The word 'warning' should appear in yellow, whereas the same command piped to plainlessshows the text without color.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.