Mastering the Cat Command in Linux: A Comprehensive Guide for Beginners
The cat command—short for concatenate—is one of the most fundamental utilities in Unix-like operating systems. It is primarily used to read, display, concatenate, and redirect file contents directly from the terminal standard output stream. Mastering cat along with its stream manipulation variants (tac and rev) forms the bedrock of command-line text processing, file creation, and shell scripting.
1. Introduction to the cat Utility & Man Page Breakdown
According to the official Linux manual page (man cat), the primary function of cat is to concatenate files and print them to the standard output (stdout).
Manual Synopsis
cat [OPTION]... [FILE]...
In Unix command syntax, items enclosed in square brackets [...] indicate optional parameters:
[OPTION]...: Flags that modify command behavior (e.g., line numbering, showing non-printing characters).[FILE]...: One or more target files to process.
Note: Because both options and target files are optional, executing
catwithout any arguments forces the utility to listen for continuous input from the standard input (stdin) stream (the keyboard).
2. Displaying and Concatenating Files
The standard usage of cat involves reading one or multiple files and outputting their contents sequentially to the terminal.
Step 1: Creating Sample Files
Using a text editor such as nano, let us create two basic text files:
# Create a.txt with content "abc"
nano a.txt
# Create b.txt with content "xyz"
nano b.txt
Step 2: Displaying a Single File
To output the contents of a single file:
cat a.txt
Output:
abc
Step 3: Concatenating Multiple Files
When given multiple file parameters, cat reads them from left to right, combining their contents in sequence:
cat a.txt b.txt
Output:
abc
xyz
3. Stream Redirection: Overwriting (>) vs. Appending (>>)
Rather than merely displaying text to the terminal screen, cat can be combined with shell redirection operators to construct new files or merge existing ones.
The Overwrite Redirection Operator (>)
The single right-angle bracket (>) redirects the standard output of cat into a specified target file. If the target file does not exist, Linux creates it. If it already exists, its existing content is completely wiped and overwritten.
# Concatenate a.txt and b.txt into a new file named c.txt
cat a.txt b.txt > c.txt
# Inspect c.txt
cat c.txt
Output:
abc
xyz
The Append Redirection Operator (>>)
The double right-angle bracket (>>) preserves existing data inside the target file and appends the new stream directly to the bottom of the file.
# Append the contents of a.txt to c.txt
cat a.txt >> c.txt
# Inspect c.txt
cat c.txt
Output:
abc
xyz
abc
4. Creating Files On-the-Fly via Interactive stdin
When cat is invoked without a file argument and paired with a redirection operator (cat > filename.txt), it transforms into an immediate, lightweight file creator.
Interactive Creation Workflow
Terminal Keyboard (stdin)
|
| Raw text typed line-by-line
v
cat Command
|
| Redirects stream via '>'
v
Target File (a.txt)
Demonstration
# Start interactive stream writing into a.txt
cat > a.txt
At this point, the terminal waits for terminal input. Type text directly into the console:
Hello there
How are you
OK
To signal to the shell that input is complete and save the file, issue the End-of-File (EOF) control character sequence: Ctrl + D.
# Verify the newly created file
cat a.txt
Output:
Hello there
How are you
OK
5. Terminal Signals: Ctrl + D vs. Ctrl + C
When working interactively with streams in Linux, understanding POSIX signals and terminal control keys is vital to prevent lost or corrupted data.
1. Ctrl + D (End-of-File / EOF)
- Mechanism: Sends a control character (
EOF) indicating the end of the input stream. - Result: Flushes the internal IO buffer, cleanly terminates the
catprocess, saves all entered lines to the target file, and returns control to the shell prompt.
2. Ctrl + C (SIGINT - Interrupt Signal)
- Mechanism: Sends a hardware interrupt signal (
SIGINT) directly to the running foreground process. - Result: Abruptly halts execution. Any unwritten text remaining in the active input buffer before the last newline may be discarded or result in incomplete file writes.
Example: Partial Writes via Signal Cancellation
cat > a.txt
Line 1
Line 2
[Press Ctrl + C]
Depending on buffer state, Line 2 may not be flushed safely to the storage drive, resulting in lost output compared to using Ctrl + D.
6. Real-World Pitfall: Trailing Newlines and Line Termination
A common beginner mistake occurs when typing text in an interactive cat session and pressing Ctrl + D immediately at the end of a sentence without pressing Enter.
The Edge Case
cat > a.txt
Hello there[Ctrl + D]
Because no Enter key (Newline character \n) was issued prior to sending EOF, the file lacks a proper terminal line break. This can cause prompt distortion in terminal emulators:
user@linux:~$ cat a.txt
Hello thereuser@linux:~$
The Correct Practice
Always issue an explicit newline (Enter) before concluding input with Ctrl + D:
cat > a.txt
Hello there
[Press Enter]
[Press Ctrl + D]
7. Alternative File Creation Method: echo vs. cat
While cat is ideal for multi-line stream entry, single-line file generation is often handled faster using the echo command.
# Creating a file using echo
echo "Hello there" > a.txt
# Inspecting content
cat a.txt
Output:
Hello there
When to use which?
- Use
echo: For single line strings, variables, or fast inline content appending (echo "data" >> log.txt). - Use
cat: For multi-line text input without launching a full GUI/CLI editor, or for merging existing files.
8. Vertical File Reversal with tac
The tac utility is literally cat spelled backward. It performs line-by-line vertical reversal of a file, printing the last line first down to the first line.
Demonstration
- Create a food list file using
cat:
cat > foods.txt
Pizza
Egg roll
Fries
Cake
Cookies
[Press Enter + Ctrl + D]
- Display the file normally using
cat:
cat foods.txt
Output:
Pizza
Egg roll
Fries
Cake
Cookies
- Display the file in reverse using
tac:
tac foods.txt
Output:
Cookies
Cake
Fries
Egg roll
Pizza
Combining tac with Stream Redirection
You can process text through tac interactively or save reversed outputs into new files:
# Interactively write list into tac and output directly to fruits.txt
tac > fruits.txt
Kiwi
Mango
Guava
[Press Enter + Ctrl + D]
# Display fruits.txt with cat
cat fruits.txt
Output:
Guava
Mango
Kiwi
Explanation: The inputs entered (
Kiwi,Mango,Guava) were processed vertically in reverse order before being stored insidefruits.txt.
9. Horizontal Character-Wise Reversal with rev
While tac reverses files vertically line-by-line, the rev utility reverses content horizontally character-by-character across each individual line.
Operational Mechanics
- Vertical Order: Preserved (Line 1 remains Line 1, Line 2 remains Line 2).
- Horizontal Order: Inverted (Left-to-right becomes Right-to-left).
Demonstration
# Read foods.txt using rev
rev foods.txt
Output:
azziP
llor ggE
seirF
ekaC
seikooc
Processing Text Strings with rev
cat > sample.txt
Hello There
How Are You
[Press Enter + Ctrl + D]
rev sample.txt
Output:
erehT olleH
uoY erA woH
10. Comparative Tool Synthesis
Summary and Key Takeaways
- Core Purpose:
catstands for concatenate. Its default behavior is reading targeted files and displaying their contents sequentially onstdout. - Flexible Syntax: Running
catwithout file arguments attaches it tostdin, transforming it into an interactive stream processor. - Overwrite Operator (
>): Wipes target file content if present and writes new stream data. - Append Operator (
>>): Preserves target file content and appends new stream data at the end. - EOF Signal (
Ctrl + D): Safely closes standard input stream, flushes buffers, and finalized file creation. - Interrupt Signal (
Ctrl + C): Forcefully terminates execution and risks dropping unflushed input data. - Proper Line Ending: Always hit
Enterbefore issuingCtrl + Dwhen creating files interactively to guarantee terminal line breaks. tacUtility: Reverses files line-by-line vertically, serving as an effective log inspection tool.revUtility: Inverts strings horizontally character-by-character while maintaining original line ordering.