15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
10.11.2023

The `less` Command in Linux: Complete Guide with Syntax, Options, and Real-World Usage

The less command in Linux is a terminal-based pager utility that allows you to view the contents of text files and command output interactively, without loading the entire file into memory. Unlike text editors such as Vim or Nano, less opens files in a read-only, paginated view, making it the go-to tool for inspecting large log files, configuration files, and command output streams on any Unix-like system.

For a quick answer: less filename opens any text file in an interactive, scrollable viewer. You can navigate forward and backward, search for patterns, and exit cleanly β€” all without modifying the file.

Why less Matters for System Administrators

When managing a Linux server, you routinely deal with files that are thousands of lines long β€” application logs, kernel messages, Apache or Nginx access logs, configuration dumps, and more. Opening these in a full editor is wasteful and carries the risk of accidental modification. The less pager loads content on demand, meaning it reads only the portion of the file currently displayed. This makes it exceptionally efficient for files that are gigabytes in size.

This behavior is fundamentally different from commands like cat, which dumps the entire file to standard output at once, or head/tail, which show only a fixed portion. less gives you full interactive control over traversal without any memory overhead proportional to file size.

If you manage a VPS Hosting environment or a Dedicated Server, less will be one of the most frequently used diagnostic tools in your daily workflow β€” particularly when tailing through /var/log/syslog, /var/log/auth.log, or application-specific log directories.

less vs. more: A Technical Comparison

The more command predates less and is its conceptual predecessor. While both are pagers, their capabilities differ significantly. The name "less" is a deliberate Unix joke: *less is more than more*.

Featurelessmore
Scroll forwardYesYes
Scroll backwardYesNo
Arrow key navigationYesLimited
Search forward (/pattern)YesYes
Search backward (?pattern)YesNo
Jump to line numberYesNo
Percentage of file readYesNo
Pipe supportYesYes
Open multiple filesYesNo
Memory usage for large filesConstant (on-demand)Higher
Available on minimal systemsSometimes not pre-installedAlmost always present

The practical takeaway: use more only when less is unavailable, such as on extremely stripped-down container images or legacy embedded systems. In all other contexts, less is strictly superior.

Basic Syntax

less [OPTIONS] filename

You can also pipe output directly into less:

command | less

Examples:

less /var/log/syslog
grep "error" /var/log/nginx/access.log | less
dmesg | less
cat /etc/nginx/nginx.conf | less

The pipe pattern is particularly powerful. Any command that produces verbose output β€” ps aux, netstat -tulnp, find / -name "*.conf" β€” becomes manageable when piped into less.

Default Navigation Keybindings

Once inside less, the following keyboard shortcuts control navigation. These are not optional flags β€” they are interactive commands you type while the file is open.

KeyAction
Space or fScroll forward one full screen
bScroll backward one full screen
Down arrow or jScroll forward one line
Up arrow or kScroll backward one line
dScroll forward half a screen
uScroll backward half a screen
gJump to the beginning of the file
GJump to the end of the file
nG or ngJump to line number n
/patternSearch forward for a pattern
?patternSearch backward for a pattern
nRepeat last search in same direction
NRepeat last search in opposite direction
qQuit less
hDisplay help screen
FFollow mode β€” like tail -f, streams new content

The F key (follow mode) deserves special attention. It turns less into a live log monitor, equivalent to tail -f, but with the added ability to press Ctrl+C to stop following and then navigate backward through the already-loaded content. This is something tail -f cannot do.

Command-Line Options Reference

These flags are passed when invoking less from the command line, modifying its behavior before the file opens.

OptionDescription
-NDisplay line numbers on the left margin
-nSuppress line numbers (default on some systems)
-iCase-insensitive search (ignores upper/lower case)
-ICase-insensitive search, even for the pattern itself
-SChop long lines instead of wrapping them (useful for wide CSV or log files)
-p patternOpen the file and jump directly to the first occurrence of the specified pattern
-cRepaint screen from top instead of scrolling (reduces flicker on slow terminals)
-gHighlight only the string found by the most recent search, not all matches
-GDisable all search result highlighting entirely
-FExit automatically if the entire file fits on one screen
-XDo not clear the screen when less exits (leaves content visible in terminal)
-RRender ANSI color escape sequences (essential when piping colored output)
-eExit automatically at the second end-of-file
+nStart at line number n
+/patternStart at the first occurrence of pattern (alternative syntax to -p)
-mShow percentage of file read in the prompt (like more)
-MShow more verbose prompt including line numbers and percentage

Practical Option Combinations

View a log file with line numbers, case-insensitive search, and no line wrapping:

less -NiS /var/log/apache2/error.log

Open a file and jump directly to the first occurrence of "segfault":

less -p "segfault" /var/log/kern.log

Pipe colored command output and preserve colors:

grep --color=always "FAILED" /var/log/auth.log | less -R

Open a file and exit immediately if it fits on one screen:

less -F /etc/hosts

Searching Within less: Advanced Techniques

The search functionality in less supports regular expressions, not just literal strings. This is a critical distinction that many users overlook.

/error|warning|critical

This pattern matches any line containing "error", "warning", or "critical" β€” using standard POSIX extended regex syntax. Combined with -i for case-insensitivity, this becomes a powerful inline log analysis tool without needing grep as a preprocessor.

Searching across multiple files:

less file1.log file2.log file3.log

Use :n to move to the next file and :p to return to the previous one. The /pattern search applies within the current file only, but you can repeat it across files manually.

Working with Multiple Files and Named Pipes

less can open multiple files in sequence:

less /var/log/syslog /var/log/kern.log /var/log/auth.log

It also works correctly with named pipes (FIFOs) and process substitution, which is useful in advanced shell scripting:

less <(journalctl -u nginx --since "1 hour ago")

This opens the output of journalctl as if it were a file, with full backward scrolling β€” something a plain pipe would not support for backward navigation in all shell environments.

Real-World Edge Cases and Pitfalls

Binary files: Running less on a binary file (compiled executables, compressed archives) will display garbled characters and may trigger a warning. Use less -f to force it open, but the output will be largely unreadable. For binary inspection, xxd or hexdump is the correct tool.

Very wide lines: Log files generated by certain Java frameworks or JSON-heavy applications often contain extremely long single lines. Without -S, less wraps these lines, making them difficult to read. The -S flag enables horizontal scrolling with the arrow keys, which is far more practical.

Compressed files: On systems with lesspipe configured (common on Debian/Ubuntu), less can transparently open .gz, .bz2, .zip, and other compressed formats. Check if it is enabled with echo $LESSOPEN. If not configured, use zless (a wrapper script) for gzip-compressed files.

Color output lost in pipes: When piping output from tools like grep --color, ls --color, or diff, the color codes are ANSI escape sequences. Without -R, less displays them as raw escape characters. Always use less -R when piping colored output.

LESSOPEN and LESSCLOSE: These environment variables define preprocessor and postprocessor scripts that less runs on files before displaying them. On a properly configured system, this allows less to display the contents of archives, PDFs, and even images (as ASCII art) transparently. This is an underused feature with significant diagnostic utility.

Configuring less Persistently with LESS Environment Variable

Rather than typing flags every time, you can set default options via the LESS environment variable in your shell profile (~/.bashrc or ~/.zshrc):

export LESS="-NiRMS"

This applies -N (line numbers), -i (case-insensitive search), -R (color rendering), -M (verbose prompt), and -S (no line wrap) to every less invocation automatically. This is a standard practice on production servers where log analysis is frequent.

Using less in Shell Scripts and Automation

While less is primarily interactive, it integrates cleanly into administrative scripts. A common pattern is to conditionally invoke it only when running in an interactive terminal:

if [ -t 1 ]; then
    some_command | less -R
else
    some_command
fi

The -t 1 test checks whether standard output is connected to a terminal. This prevents less from blocking non-interactive pipelines or cron jobs.

less in the Context of Server Management

On a VPS with cPanel or any control-panel-managed environment, less remains indispensable for SSH-based administration even when a GUI is available. Control panels expose limited log views; direct SSH access with less gives you unfiltered, real-time visibility into system behavior.

When provisioning Dedicated Servers for high-traffic applications, structured log analysis workflows built around less, grep, awk, and sed form the backbone of incident response. Knowing how to navigate a 2 GB access log efficiently without loading it into memory is a foundational sysadmin skill.

For teams managing Email Hosting infrastructure, less is the standard tool for inspecting Postfix mail logs (/var/log/mail.log) and Dovecot authentication logs, where line-by-line backward navigation is essential for tracing delivery failures.

Quick-Reference Decision Matrix

Use this matrix to decide which tool to reach for when viewing file content:

ScenarioRecommended Tool
View a large log file interactivelyless -NiS
Monitor a log file in real timeless +F or tail -f
View last N lines onlytail -n N
View first N lines onlyhead -n N
Search and filter without interactiongrep
View a compressed .gz filezless or less with lesspipe
Inspect binary/hex contentxxd or hexdump
View with syntax highlightingbat (third-party pager)
Quick dump of small filecat
Minimal system, less unavailablemore

Key Technical Takeaways

  • less loads file content on demand β€” memory usage does not scale with file size, making it safe for multi-gigabyte files.
  • The -R flag is mandatory when piping colored output; omitting it produces unreadable escape sequences.
  • Follow mode (F key) provides tail -f functionality with the added ability to scroll backward through buffered content.
  • Regular expressions are supported natively in search patterns β€” no need to pre-filter with grep for pattern matching.
  • Set export LESS="-NiRMS" in your shell profile to apply sensible defaults globally.
  • Use less <(command) with process substitution for full interactive navigation of command output, including backward scrolling.
  • The LESSOPEN variable enables transparent decompression and format conversion β€” verify it is configured on your servers.
  • Never use cat on large files when less is available; it saturates the terminal buffer and provides no navigation capability.

Frequently Asked Questions

What is the difference between less and cat in Linux?

cat outputs the entire file content to standard output at once, with no interactivity or pagination. less opens the file in an interactive pager where you can scroll, search, and navigate. For any file longer than your terminal height, less is the correct tool.

Can less edit files?

No. less is strictly a read-only viewer. It does not modify files under any circumstances. To edit, use vim, nano, or another text editor.

How do I search for a word in less?

While the file is open in less, type /word and press Enter to search forward. Use ?word to search backward. Press n to jump to the next match and N to go to the previous one. Searches support regular expressions.

Why does less show garbled characters when I pipe colored output?

ANSI color escape sequences are not rendered by default. Pass the -R flag β€” either as less -R or by setting export LESS="-R" in your shell profile β€” to render colors correctly.

Is less available on all Linux distributions?

less is included by default on virtually all major Linux distributions including Debian, Ubuntu, CentOS, RHEL, Fedora, and Arch Linux. On minimal Docker base images or Alpine Linux, it may need to be installed explicitly with apk add less or the equivalent package manager command.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started