Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
less Command in Linux: View, Navigate, and Search Text Files
AI Executive SummaryWebsiteVidya AI

9 min read

Learn less command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What less Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
less Command in Linux: View, Navigate, and Search Text Files — syntax, flags, and practical terminal workflow diagram
less Command in Linux: View, Navigate, and Search Text Files — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-N--LINE-NUMBERSDisplay a line number at the beginning of each line.
-S--chop-long-linesTruncate lines longer than the screen width rather than wrapping them.
-i--ignore-caseIgnore case in searches unless pattern contains uppercase letters (smart case).
-F--quit-if-one-screenAutomatically exit if the entire file fits on the initial screen.
-X--no-initDisable terminal initialization string (preserves viewed contents on screen upon exit).
-R--RAW-CONTROL-CHARSOutput ANSI 'color' escape sequences in raw form, preserving terminal colors.
+F+FStart in follow mode (monitor growing files in real-time, similar to tail -f).
-m--long-promptDisplay 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.

Advertisement

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

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

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Press the 'q' key. If you are currently in follow mode (+F), press Ctrl+C first to pause following, then press 'q' to quit.
more is an older pager that historically allowed only forward navigation. less allows both forward and backward scrolling, regex searching, marks, and does not require reading the entire file before displaying.
Press 'g' to jump to the very beginning (line 1) of the file, and press 'G' (Shift+g) to jump directly to the end of the file.
Use the zless command (e.g. zless /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.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout