How to Preserve ANSI Color Output When Piping ls Through less in Bash


2 views

When working in terminal environments, many developers rely on colored output for better readability. This is particularly true for commands like ls which use colors to distinguish between file types:

ls --color=auto
# Without piping, shows colorful output
# But when piped:
ls --color=auto | less
# Colors disappear!

The issue occurs because by default, less doesn't interpret ANSI color escape sequences. These sequences look like:

\033[31mRed Text\033[0m
# Where:
# \033[31m - Sets red color
# \033[0m  - Resets formatting

Here are the most effective ways to preserve colors:

1. The -R Flag for less

The simplest solution is to use less -R which interprets color codes correctly:

ls --color=auto | less -R

2. Permanent Alias Solution

For frequent use, add this to your ~/.bashrc or ~/.zshrc:

alias lsc='ls --color=auto'
alias lessc='less -R'
# Then use:
lsc | lessc

3. Environment Variable Approach

For system-wide solution, modify the LESS environment variable:

export LESS='-R'
# Now this works:
ls --color | less

For power users, create a ~/.less config file:

# ~/.less
# Enable raw control characters
-r

# And optionally:
# -X: keep output on screen after exit
# -F: quit if less than one screen
-RFX

If colors still don't appear:

  • Verify ls actually outputs colors: ls --color=auto > output.txt and check the file
  • Ensure your terminal supports ANSI colors
  • Check if dircolors is properly configured

Many Linux users encounter this frustrating scenario:

ls --color=auto | less

The vibrant directory listings suddenly become monochromatic. This occurs because less by default strips ANSI color codes when processing piped input.

When you run ls --color=auto directly, it detects terminal support and outputs color codes. However, when piping:

  1. The color codes get interpreted as control characters
  2. less filters these by default for "clean" output
  3. The terminal never receives the color information

Method 1: Using less -R

ls --color=auto | less -R

The -R flag tells less to raw interpret ANSI color codes.

Method 2: Permanent Alias

alias lsl='ls --color=auto | less -R'

Add this to your ~/.bashrc for persistent usage.

Method 3: Environment Variable

export LESS=-R

This makes -R the default behavior for all less usage.

For custom color preservation with grep:

grep --color=always "pattern" file.txt | less -R

Combining multiple commands:

ls -la --color=always | grep --color=always "pattern" | less -R

Colorized output isn't just aesthetic - it significantly improves:

  • Directory navigation speed
  • Pattern recognition in logs
  • Error vs warning differentiation

If colors still don't appear:

  1. Verify terminal supports colors: echo -e "\e[31mRED\e[0m"
  2. Check ls color settings: dircolors -p
  3. Ensure --color flag is properly set