Viewing Files with cat, less, head, and tail

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 19 of 205

Text files are everywhere on a Linux system: configuration, source code, logs, notes. Four commands cover almost every way of reading them from the terminal. cat prints a whole file, less lets you page through it, head shows the beginning, and tail shows the end. Each one suits a different situation, and knowing which to reach for saves a lot of scrolling.

Understanding the Concept

All four commands read a file and write text to standard output, which is normally your terminal. None of them modifies the file. The differences are in how much they show and how they let you interact:

CommandShowsInteractive
catThe entire file at onceNo
lessThe file one screen at a timeYes: scroll and search
headThe first lines (10 by default)No
tailThe last lines (10 by default)No (but can follow growth with -f)

The examples below use two small files:

printf 'line one\nline two\nline three\n' > short.txt
seq 1 25 > nums.txt

The first creates a three-line file with printf. The second uses seq to write the numbers 1 to 25, one per line.

Printing a Whole File with cat

The name cat comes from "concatenate". With one file it prints the content:

cat short.txt

Output:

line one
line two
line three

The command is the right choice for short files, where you want everything at once. For a file with thousands of lines, the content would scroll past faster than you could read it, and less is a better tool.

Numbering Lines

The option -n puts a line number in front of every line:

cat -n short.txt

Output:

     1	line one
     2	line two
     3	line three

Seeing Hidden Characters

Invisible characters can cause bugs, such as trailing spaces or tabs in a script. The option -A makes them visible. A tab appears as ^I, and the end of each line is marked with $:

printf 'a\tb  \n' | cat -A

Output:

a^Ib  $

The $ sits right after two spaces, which shows that the line ends with trailing spaces that you could not see before.

Squeezing Blank Lines

The option -s collapses runs of blank lines into a single blank line:

printf 'alpha\n\n\n\nbeta\n' > gaps.txt
cat -s gaps.txt | cat -A

Output:

alpha$
$
beta$

The three blank lines became one. The second cat -A is only there to show where lines end.

Joining Files

Given several names, cat prints them one after another, which is the source of its name. Combined with redirection, this joins files:

printf 'first\n' > p1
printf 'second\n' > p2
cat p1 p2 > joined.txt
cat joined.txt

Output:

first
second

A related command, tac (the word cat reversed), prints the lines in reverse order:

tac short.txt

Output:

line three
line two
line one

Reading Standard Input

When no file is given, cat reads from standard input and copies it to the output:

echo typed | cat

Output:

typed

Missing Files

cat nope.txt
echo "status=$?"

Output:

cat: nope.txt: No such file or directory
status=1

Reading Page by Page with less

less opens a file in a pager, a program that displays one screen at a time and waits for your keys. It does not load the whole file first, so it starts immediately even on very large files.

less nums.txt

Inside less, these keys are the most useful:

KeyAction
Space or fForward one screen
bBack one screen
Down arrow or jForward one line
Up arrow or kBack one line
gJump to the start of the file
GJump to the end of the file
/textSearch forward for text
?textSearch backward for text
n and NNext and previous match
qQuit

After typing /text and pressing Enter, less highlights the matches and jumps to the first one. Pressing n moves to the next.

Useful options include -N to show line numbers, -S to cut long lines instead of wrapping them, and -F to quit automatically when the whole file fits on one screen. Because of that last option, less -F behaves like cat for short input:

printf 'one\ntwo\nthree\n' | less -F -X

Output:

one
two
three

(The -X option stops less from clearing the screen on exit, so the text stays visible.) The manual page for less is itself shown with a pager, which is why the keys above work in man too.

Showing the Start of a File with head

head prints the first 10 lines by default:

head nums.txt

Output:

1
2
3
4
5
6
7
8
9
10

Use -n to choose the number of lines:

head -n 3 nums.txt

Output:

1
2
3

The short form head -3 also works in GNU head, but -n 3 is the portable choice. A negative count means "everything except the last N lines":

head -n -22 nums.txt

Output:

1
2
3

The file has 25 lines, so removing the last 22 leaves the first three.

The option -c counts bytes instead of lines:

head -c 10 nums.txt

Output:

1
2
3
4
5

The ten bytes are the five digits 1 to 5, each followed by a newline character, so the output looks like five lines.

Showing the End of a File with tail

tail prints the last 10 lines by default, and -n changes the count:

tail -n 3 nums.txt

Output:

23
24
25

A count with a plus sign changes the meaning: +N means "start at line N and print the rest".

tail -n +23 nums.txt

Output:

23
24
25

The same three lines appear, because line 23 is where the output begins.

Extracting a Range of Lines

Combining head and tail with a pipe prints any range. To see lines 10 to 12, take the first 12 lines and keep the last three of those:

head -n 12 nums.txt | tail -n 3

Output:

10
11
12

Several Files at Once

When you give head or tail more than one file, each section starts with a header naming the file:

head -n 2 short.txt nums.txt

Output:

==> short.txt <==
line one
line two

==> nums.txt <==
1
2

Following a Growing File

The option -f (follow) keeps tail running and prints new lines as they are added to the file. It is the standard way to watch a log:

tail -f app.log

If another program appends three events to app.log, the terminal shows each one as it arrives:

event 1
event 2
event 3

The command does not end by itself. Press Ctrl + C to stop it. The variant tail -F also keeps following when the log file is rotated, meaning replaced by a new file with the same name, which is common for server logs.

Practical Applications

Counting Before Reading

Before opening a file, check how big it is. The wc -l command counts lines:

wc -l nums.txt

Output:

25 nums.txt

A short file suits cat. A longer one calls for less, or head to peek at the beginning.

Inspecting the Start of Command Output

All four commands also read from a pipe. This shows only the first three entries of a long directory listing:

ls /usr/bin | head -n 3

The exact names depend on your system, but you receive only three lines instead of hundreds.

Checking a File Type by Its First Bytes

Binary files begin with a recognizable signature. Printing the first four bytes of a program in readable form, with head -c and od -c, shows the signature of the Linux executable format:

head -c 4 /bin/ls | od -c

Output:

0000000 177   E   L   F
0000004

The bytes are the value 177 in octal followed by the letters ELF, which stands for Executable and Linkable Format. This is why you should not use cat on binary files: the raw bytes can confuse your terminal.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Viewing Files with cat, less, head, and tail and get answers drawn from it.

Signed-in readers only.