less Command in Linux: View, Navigate, and Search Text Files
Learn less command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn less command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What less Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Mastering the less command in linux provides engineers with the premier terminal pager for inspecting files and command pipelines of arbitrary size. Originating as an enhanced replacement for the older more utility—coining the Unix proverb 'less is more'—less allows full bidirectional navigation, interactive regular expression searching, dynamic mark placement, and live stream following.
The less command in Linux is a terminal pager that displays text files or command output page-by-page, allowing both forward and backward navigation and regex searching without loading the entire file into memory. Run less /var/log/syslog to view a file, press /pattern to search forward, or run less +F to follow live appends like tail -f.
A primary reason less is ubiquitous across modern Linux systems is its memory efficiency. When opening a 20-gigabyte application log or database dump in a standard text editor like nano or vim, the editor attempts to load the entire document into system RAM, frequently causing the process to crash or lock the terminal. In contrast, less opens files instantly, reading only the viewport chunk necessary to render the current screen.
Whether troubleshooting systemd journal streams, browsing source code, inspecting manual pages, or evaluating piped outputs from git diff and kubectl, mastering less's keyboard navigation and startup flags significantly accelerates terminal workflow efficiency.
What less Does and When to Use It
Under the hood, less interfaces with the terminal subsystem via terminfo/ncurses capabilities, placing the controlling terminal into 'raw' or 'cbreak' mode. In this mode, character echo and line buffering are disabled, allowing less to capture single keystrokes (such as j, k, /, q) instantaneously without waiting for a Return keypress.
When opening disk files, less makes extensive use of lseek(2) to jump directly to file offsets, maintaining an in-memory page table of discovered line numbers and byte positions. When reading from pipes or non-seekable streams (like standard input), less buffers incoming data dynamically into an internal circular memory structure or temporary disk cache, allowing backward scrolling even over unidirectional streams. Its search subsystem compiles regular expressions using POSIX regcomp(3) or PCRE, highlighting matches across screen rows via terminal ANSI styling sequences.
Under the hood, less gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -N, -S, -i, -F turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The less utility is packaged in less across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether less is installed and inspect which binary path and version your shell resolves:
type -a less
less --version 2>/dev/null || man -f less
# Illustrative output (reviewed against documentation)
less is /usr/bin/less
less (less)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y less
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y less
# Arch Linux
sudo pacman -S --noconfirm less
# Alpine Linux
sudo apk add --no-cache less
Command Syntax, Arguments, and Exit Status Codes
less [OPTIONS] [FILE...]
The basic command invocation is less [OPTIONS] [FILE...]. If multiple files are provided as arguments, less opens the first file and allows you to cycle through subsequent files using the :n (next) and :p (previous) internal commands.
Options can be specified either on the command line upon launch or toggled interactively from within less by typing the option flag followed by Enter. For example, typing -N inside less toggles line number display on and off dynamically.
0— Successful termination; user exited pager normally via 'q'.1— Operational failure; file not found, permission denied, or invalid option.2— Command-line syntax error.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-N | --LINE-NUMBERS | Display a line number at the beginning of each line. |
-S | --chop-long-lines | Truncate lines longer than the screen width rather than wrapping them. |
-i | --ignore-case | Ignore case in searches unless pattern contains uppercase letters (smart case). |
-F | --quit-if-one-screen | Automatically exit if the entire file fits on the initial screen. |
-X | --no-init | Disable terminal initialization string (preserves viewed contents on screen upon exit). |
-R | --RAW-CONTROL-CHARS | Output ANSI 'color' escape sequences in raw form, preserving terminal colors. |
+F | +F | Start in follow mode (monitor growing files in real-time, similar to tail -f). |
-m | --long-prompt | Display a detailed status prompt showing percentage through file. |
The combination less -RS is standard for log inspection: -R preserves ANSI color formatting from colorized loggers, while -S chops long lines horizontally instead of wrapping them, preserving column alignment across structured log records. You can scroll horizontally using the left and right arrow keys.
Another popular combination is less -FX: -F exits immediately if the content fits on a single terminal screen, while -X leaves the output visible in your terminal scrollback after quitting, replicating the behavior of cat for short files while providing pager navigation for long ones.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Open a File and Display Line Numbers with -N
Inspect a system log file with 1-based line numbers displayed in the left margin.
less -N /var/log/syslog
# Illustrative output (reviewed against documentation)
1 Oct 22 06:25:01 server systemd[1]: Starting Daily apt download activities...
2 Oct 22 06:25:05 server systemd[1]: Finished Daily apt download activities.
3 Oct 22 07:10:02 server CRON[18412]: (root) CMD (/usr/local/bin/backup.sh)
/var/log/syslog (press q to quit)
The -N flag prefixes each line with its ordinal line number, making it easy to cross-reference entries.
2. Follow Live File Growth Like tail -f Using +F
Open an active application log and stream real-time updates as new lines are appended.
less +F /var/log/nginx/access.log
# Illustrative output (reviewed against documentation)
198.51.100.12 - - [22/Oct/2026:16:01:10 +0000] "GET /api HTTP/1.1" 200 452
192.0.2.89 - - [22/Oct/2026:16:01:12 +0000] "POST /login HTTP/1.1" 200 120
Waiting for data... (interrupt to abort)
Starting with +F follows live file appends. Pressing Ctrl+C pauses follow mode to allow scrolling backward, and pressing Shift+F resumes following.
3. Search Forward and Backward with Regular Expressions
Search for specific error terms interactively inside less using forward and backward slash commands.
less /var/log/nginx/error.log
# Inside less, type:
/critical
# Press 'n' to go to next match, 'N' for previous match
# Type '?' to search backward:
?upstream
# Illustrative output (reviewed against documentation)
2026/10/22 16:12:00 [crit] 1104#1104: *42 SSL_do_handshake() failed
2026/10/22 16:14:22 [error] 1104#1104: *48 connect() failed (111: Connection refused) while connecting to upstream
The / key searches forward from the current line, while ? searches backward. Matches are highlighted across the document.
4. Chop Long Lines Horizontally to Preserve Column Tables
Prevent ragged line wrapping on wide columnar data using -S.
ps -ef | less -S
# Illustrative output (reviewed against documentation)
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 Oct20 ? 00:00:03 /sbin/init
root 2 0 0 Oct20 ? 00:00:00 [kthreadd]
www-data 1104 1 0 Oct20 ? 00:00:12 nginx: master process /usr/s...
The -S flag disables automatic line wrapping. Use the Left and Right arrow keys to scroll horizontally across wide lines.
5. Preserve Terminal ANSI Color Escape Codes with -R
View colorized command output without displaying raw ANSI escape sequences.
git log --graph --oneline --color=always | less -R
# Illustrative output (reviewed against documentation)
* 7f9a12c (HEAD -> main) Add security policy documentation
* 3b8c41d Fix memory leak in auth worker
* e21d94f Update database migration schema
The -R flag interprets ANSI color codes properly, keeping branch graphs and colored diffs readable.
6. Navigate Between Multiple Files Sequentially
Open multiple configuration files simultaneously and cycle between them.
less /etc/hosts /etc/resolv.conf
# Type ':n' to move to /etc/resolv.conf
# Type ':p' to return to /etc/hosts
# Illustrative output (reviewed against documentation)
127.0.0.1 localhost
127.0.1.1 prod-server-01
/etc/hosts (file 1 of 2) (press :n for next file)
less tracks the file list in memory; :n advances to the next file and :p moves back to the previous one.
Real-World Workflows, Pipelines, and Shell Automation
Production Incident Triage: Investigating Crash Logs with Follow Toggling
Examine system crash logs with less, toggle live stream monitoring, and search backward for root-cause exceptions.
#!/usr/bin/env bash
set -euo pipefail
CRASH_LOG="/var/log/application/error.log"
echo "Launching triage viewer with smart-case search, line numbers, and follow mode..."
# -R: Colors, -N: Line numbers, -S: No line wrapping, +F: Follow mode
less -RNS +F "$CRASH_LOG"
# Illustrative output (reviewed against documentation)
1 2026-10-22 16:30:00 [INFO] Worker pool initialized
2 2026-10-22 16:30:05 [WARN] Redis latency spike: 250ms
3 2026-10-22 16:30:12 [ERROR] Fatal: OutOfMemoryError in queue processor
Waiting for data... (interrupt to abort)
Engineers can press Ctrl+C to stop following, press ?OutOfMemory to search backward for root causes, and press Shift+F to re-engage live monitoring.
Custom Git and Environment Pager Configuration
Configure less as the default system-wide pager with optimal flag defaults via environment variables.
#!/usr/bin/env bash
set -euo pipefail
# Add optimal less flags to ~/.bashrc
cat << 'EOF' >> ~/.bashrc
# Configure default less options:
# -R: raw ANSI color, -i: smart case search, -M: verbose status prompt, -X: keep output
export LESS="-R -i -M -X -S"
export PAGER="less"
export SYSTEMD_PAGER="less"
EOF
echo "Pager defaults successfully configured."
# Illustrative output (reviewed against documentation)
Pager defaults successfully configured.
Setting the LESS environment variable automatically applies these flags whenever git, man, journalctl, or less is invoked.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding less inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
less is a read-only viewer and does not modify files. However, pressing 'v' inside less will open the current file in your default editor ($EDITOR, such as vim or nano). If running less as root, editing sensitive files can lead to accidental changes.
When running less on untrusted files or with sudo privileges, be aware of the shell breakout feature. Pressing '!bash' inside less opens a shell with the privileges of the running process. To disable this in secure environments, pass the -E (--quit-at-eof) or -r flag, or set the LESSSECURE=1 environment variable.
Setting export LESSSECURE=1 forces less into a secure sandbox mode: shell escapes (!), editor invocation (v), and opening new files (:e) are completely disabled, making it safe for restricted environments.
GNU/Linux, BSD, and BusyBox Implementation Differences
less is the default pager on virtually all modern Linux distributions (Ubuntu, Debian, RHEL, Fedora, Arch). However, on minimal Docker images based on Alpine Linux, less may not be installed; instead, BusyBox provides a minimal pager or more.
BusyBox's less applet supports basic forward/backward navigation and / search, but lacks advanced features like -R (color escapes), +F (live follow), and marks. For full support on Alpine containers, run apk add --no-cache less.
Troubleshooting Common Errors and Diagnostics
Raw ANSI color escape codes appear as garbage characters (e.g. ^[[31m)
Root Cause: less is escaping control characters by default, rendering ANSI color codes as literal text symbols instead of formatting terminal colors.
Resolution: Pass the -R (--RAW-CONTROL-CHARS) flag or add -R to your LESS environment variable.
less -R /var/log/application.log
Terminal screen clears completely when quitting less
Root Cause: The terminal's alternate screen buffer (smcup/rmcup) is invoked by default, clearing the viewed text upon exit.
Resolution: Pass the -X (--no-init) flag to keep the last viewed page visible on your terminal screen.
less -X file.txt
less: command not found in Alpine Docker container
Root Cause: Minimal container distributions omit the standalone less package to minimize image size.
Resolution: Install the full less package via apk or use the BusyBox more fallback.
apk add --no-cache less
Alternatives, Related Commands, and Related Tutorials
- Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - tee Command in Linux: Split and Redirect Streams with Examples — Practical syntax, flags, and examples for
tee. - tail Command in Linux: Output End of Files and Follow Live Logs — Practical syntax, flags, and examples for
tail. - xargs Command in Linux: Build and Execute Command Lines from Stdin — Practical syntax, flags, and examples for
xargs. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
/var/log/nginx/access.log.1.gz) or ensure lesspipe is active in your environment, which allows less to decompress and view .gz, .tar, and .zip files automatically.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!