Overview
less is a powerful terminal pager that displays file contents one screen at a time, allowing forward and backward navigation, searching, and filtering. Unlike the older more command, less allows backward movement through files and doesn't require reading the entire file before starting. The name reflects the Unix philosophy: "less is more" - it does more with less initial overhead. It's the default pager for man pages, git logs, and many other Linux commands.
Why "less" Instead of "more"?
The more command was the original Unix pager, but it had significant limitations: forward-only scrolling, had to buffer the entire file, and limited search capabilities. less was created as an improved alternative that addresses all these issues while maintaining backward compatibility. Today, less is the standard pager on virtually all Linux systems, and even the "more" command is often symlinked to less for compatibility.
Essential Navigation Keys
| Key | Action | Notes |
|---|---|---|
| Space, f, Page Down | Forward one page | Most common navigation |
| b, Page Up | Backward one page | Not available in more |
| d, Ctrl+D | Forward half page | Smooth scrolling |
| u, Ctrl+U | Backward half page | Smooth scrolling |
| j, Enter, Down Arrow | Forward one line | Fine-grained control |
| k, Up Arrow | Backward one line | Fine-grained control |
| g, Home | Go to beginning | Jump to start of file |
| G, End | Go to end | Jump to end of file |
| q, Q | Quit less | Exit immediately |
| h | Help | Show all commands |
Example 1: Basic File Viewing
$ less filename.txt$ less /var/log/syslog$ less /etc/passwd
Opens a file for viewing with full navigation capabilities. less loads content incrementally, so it starts instantly even with huge files.
Advantages over cat:
- Doesn't flood your terminal with output
- Allows scrolling and searching
- Handles files larger than terminal buffer
- Preserves terminal state after exiting
- Works efficiently with gigabyte-sized log files
Example 2: Searching Within Files
# While in less:
/pattern # Search forward for pattern
?pattern # Search backward for pattern
n # Go to next match
N # Go to previous match
/ # Repeat last forward search
? # Repeat last backward search
less provides powerful search capabilities with regular expression support. Searches are case-sensitive by default.
Search examples:
- /error - Find next occurrence of "error"
- /[Ee]rror - Case-insensitive search (matches Error or error)
- /^ERROR - Lines starting with ERROR
- /error.*failed - Lines with error followed by failed
- ?warning - Search backward for warning
Example 3: Case-Insensitive Search
$ less -i filename.txt # Case-insensitive search mode$ less -I filename.txt # Always case-insensitive (even if uppercase in pattern)# Or toggle while viewing:
-i # Toggle case-sensitivity
The -i option makes searches case-insensitive when the search pattern is all lowercase. If you use uppercase letters in your pattern, the search becomes case-sensitive.
The -I option makes searches case-insensitive regardless of pattern case.
Examples with -i:
- /error matches error, Error, ERROR (lowercase pattern)
- /Error matches only Error (uppercase in pattern)
Example 4: Display Line Numbers
$ less -N filename.txt # Show line numbers# Or toggle while viewing:
-N # Toggle line numbers on/off
The -N option displays line numbers in the left margin. Extremely useful for:
- Referencing specific lines in code reviews
- Debugging: Correlating error messages with line numbers
- Configuration files: Finding specific directives
- Documentation: Citing specific sections
- Comparing with editor line numbers
Example 5: Follow File Growth (like tail -f)
$ less +F /var/log/syslog # Start in follow mode# Or while viewing:
F # Enter follow mode
Ctrl+C # Exit follow mode (back to normal navigation)
Follow mode makes less behave like "tail -f", continuously displaying new content appended to the file. Perfect for monitoring log files in real-time.
Advantages over tail -f:
- Can press Ctrl+C to stop following and scroll back through history
- Search through existing content before resuming follow
- Use all less navigation and search features
- Press F again to resume following from any point
Example 6: View Multiple Files
$ less file1.txt file2.txt file3.txt# Navigation between files:
:n # Next file
:p # Previous file
:e filename # Examine (open) new file
:d # Remove current file from list
less can manage multiple files simultaneously, allowing you to navigate between them without exiting.
Multi-file scenarios:
- Comparing configuration files across environments
- Reviewing related log files sequentially
- Examining multiple code files in a debugging session
- Reading documentation split across multiple files
# View all Python files in directory
$ less *.py
# View logs from multiple services
$ less /var/log/nginx/access.log /var/log/nginx/error.log /var/log/apache2/access.log
Example 7: Pipe Command Output to less
$ ps aux | less$ dmesg | less$ find / -name "*.conf" 2>/dev/null | less$ grep -r "error" /var/log/ | less$ history | less
less is the standard pager for viewing command output that's too long for one screen. Any command that produces lots of output benefits from piping to less.
Common patterns:
- Process listings: ps, top output saved to file
- Search results: grep, find with many results
- System information: dmesg, journalctl
- Command history: Browsing shell history
- Directory listings: Large ls -la output
Example 8: Syntax Highlighting for Source Code
$ less -R script.sh # Preserve ANSI color codes$ source-highlight -f esc --out-format=esc256 script.sh | less -R$ pygmentize -g script.py | less -R# Or use lesspipe (if installed):
$ export LESSOPEN="| /usr/bin/lesspipe %s"
$ less script.py # Automatic syntax highlighting
The -R option makes less interpret ANSI color codes, enabling syntax highlighting from external tools.
Setup for permanent syntax highlighting:
- Install source-highlight or pygments
- Install lesspipe: "sudo apt install lesspipe" (Debian/Ubuntu)
- Add to ~/.bashrc: export LESSOPEN="| /usr/bin/lesspipe %s"
- Now "less script.py" automatically highlights code
Example 9: Mark Positions and Jump Back
# While viewing in less:
m a # Mark current position as 'a'
m b # Mark current position as 'b'
' a # Jump to mark 'a'
' b # Jump to mark 'b'
'' # Jump to previous position before last jump
Marks allow you to bookmark positions in a file and quickly jump between them. Use any letter (a-z) as a mark identifier.
Use cases:
- Mark important sections in long documents for quick reference
- Bookmarking errors while reviewing log files
- Comparing sections: mark first location, navigate to second, jump back
- Reading technical docs: mark different sections for cross-reference
Example 10: Advanced Options and Customization
$ less -S file.txt # Chop long lines (don't wrap)$ less -s file.txt # Squeeze multiple blank lines$ less +100 file.txt # Start at line 100$ less +/pattern file.txt # Start at first match of pattern$ less -M file.txt # More verbose prompt (shows line numbers)$ less -X file.txt # Don't clear screen on exit
less offers extensive customization for different viewing scenarios:
- -S (chop lines): Essential for viewing wide data files, logs with long lines. Use arrow keys to scroll horizontally.
- -s (squeeze blanks): Useful for files with excessive spacing
- +N (start at line): Jump directly to specific line number
- +/pattern: Start viewing at first match of search pattern
- -M (verbose prompt): Shows percentage, line numbers in status line
- -X (no screen clear): Leaves content on screen after quitting
# Configure default less behavior in ~/.bashrc:
export LESS='-iMSR' # Case-insensitive, verbose, chop, colors
export LESS='-FRSX' # Quit if one screen, don't clear, chop
# Combine multiple options:
$ less -iNSM largefile.log # Case-insensitive, numbers, chop, verbose
Advanced less Commands
| Command | Action | Use Case |
|---|---|---|
| &pattern | Display only lines matching pattern | Filter log files to show only errors |
| &!pattern | Display only lines NOT matching pattern | Hide debug messages, show everything else |
| s filename | Save current view to file | Export filtered or marked sections |
| | command | Pipe current file to shell command | Process content with external tools |
| ! command | Execute shell command | Run commands without leaving less |
| = or Ctrl+G | Show file info | Display filename, line numbers, byte position |
| v | Edit current file | Open file in $EDITOR (vi/vim/nano) |
Filtering Example in less
# While viewing a log file:
&ERROR # Show only lines containing ERROR
& # Show all lines again (clear filter)
&!DEBUG # Show all lines except those with DEBUG
&^Nov 07 # Show only lines starting with "Nov 07"
Filtering is incredibly powerful for large log files. Unlike grep, you maintain context and can toggle filters on/off without losing your place.
Environment Variables
export LESS="-iMSR" # Default less optionsexport LESSOPEN="| lesspipe %s" # Preprocessor for compressed filesexport EDITOR=vim # Editor for 'v' commandexport PAGER=less # Set less as system pager
These environment variables customize less behavior system-wide. Add them to ~/.bashrc or ~/.profile for persistence.
Comparing less vs Similar Tools
| Tool | Best For | Limitations |
|---|---|---|
| less | General file viewing, logs, documentation | Not for editing (view-only) |
| more | Legacy systems, basic forward-only viewing | Can't scroll backward, limited features |
| cat | Quick dumps, piping, combining files | No navigation, floods terminal |
| head | First N lines only | No navigation, fixed output size |
| tail | Last N lines, following logs | Limited context, can't scroll back easily |
| vim/nano | Editing files | Overkill for viewing, risk of accidental edits |
Common Pitfalls
- Binary files: less can display binary files but shows gibberish. Use "file" command first to check file type.
- Very long lines: Without -S, extremely long lines wrap and can be confusing. Use -S for files with long lines.
- Encoding issues: Files with wrong encoding may display garbage. Check with "file -i filename".
- Follow mode confusion: In follow mode (F), file might not update if application holds file handle. Try Ctrl+C then F to refresh.
- Search regex syntax: less uses POSIX regular expressions, slightly different from Perl/Python regex.
Pro Tips and Workflows
- Efficient log analysis: less +F /var/log/syslog, watch for issues, Ctrl+C, search backward with ?error, investigate, press F to resume
- Quick file comparison: Open multiple files, mark important lines, use :n/:p to switch between files
- Configuration review: less -N /etc/nginx/nginx.conf with line numbers to reference specific directives
- Documentation browsing: Use marks (ma, mb) to bookmark different sections for quick cross-reference
- Debugging output: Run command | less, use &pattern to filter to relevant lines
- Archive exploration: Install lesspipe, then "less archive.tar.gz" to browse contents
- Man page power user: man pages use less - all these techniques work there too
- Git log browsing: git log opens in less - use / to search commits, g/G to jump
- Horizontal scrolling: For CSV or wide tables, use -S and arrow keys
- Script integration: Use -X in scripts to leave output visible after less exits
Related Commands
- more: Original Unix pager, forward-only (often symlinked to less)
- most: Alternative pager with multiple windows and syntax highlighting
- bat: Modern cat replacement with syntax highlighting and git integration
- cat: Concatenate and display files (no paging)
- head/tail: View beginning/end of files
- pg: Old System V pager (rarely used today)
- view: Read-only vim mode (alternative for viewing with editing capabilities)