📄 The cat Command

Concatenate and Display File Contents

cat [OPTION]... [FILE]...

Overview

The cat (concatenate) command is one of the most frequently used commands in Linux. Originally designed to concatenate files and send the output to standard output (usually your terminal), it's commonly used to display file contents, create files, append data, and combine multiple files. Despite its simplicity, cat is an essential tool in every Linux administrator's toolkit.

Primary Functions:

  • Display file contents to the terminal
  • Concatenate multiple files together
  • Create new files with content
  • Append content to existing files
  • Number lines in output
  • Show special characters and whitespace

Common Options

Option Description
-n Number all output lines
-b Number non-empty output lines
-s Squeeze multiple adjacent blank lines into one
-E Display $ at the end of each line
-T Display TAB characters as ^I
-A Equivalent to -vET (show all special characters)
-v Display non-printing characters (except tabs and newlines)

Detailed Examples

Example 1

Basic File Display

The most common use of cat is to display the contents of a file to the terminal.

# Display the contents of /etc/os-release cat /etc/os-release
NAME="Oracle Linux Server" VERSION="8.10" ID="ol" ID_LIKE="fedora" VARIANT="Server" VARIANT_ID="server" VERSION_ID="8.10" PLATFORM_ID="platform:el8" PRETTY_NAME="Oracle Linux Server 8.10"
Explanation: This displays the entire contents of the os-release file, which contains operating system identification data. The cat command reads the file and outputs it directly to your terminal. This is the most straightforward use case - simply viewing what's inside a file.
Real-World Use: System administrators frequently use this to quickly view configuration files, log files, or check system information files without opening an editor.
Example 2

Displaying Multiple Files Sequentially

Cat can display multiple files one after another, which is actually where it gets its name (concatenate).

# Display contents of multiple log files in sequence cat /var/log/messages.1 /var/log/messages.2 /var/log/messages.3
Dec 15 10:23:45 server kernel: USB disconnect, device 2 Dec 15 10:25:12 server systemd: Started Session 1234 of user craig Dec 15 11:30:00 server cron: (root) CMD (/usr/local/bin/backup.sh) Dec 16 08:15:33 server sshd[5678]: Accepted publickey for admin Dec 16 09:22:10 server kernel: Out of memory: Killed process 9012 Dec 17 14:45:22 server systemd: Stopping firewalld.service
Explanation: When you provide multiple filenames, cat reads and displays them in the order specified. This is particularly useful when you have rotated log files and want to see the sequence of events across multiple files without opening each one separately.
Pro Tip: You can use wildcards to display multiple files: cat /var/log/messages.* will display all files matching that pattern in alphabetical order.
Example 3

Creating a New File with cat

Using output redirection, cat can create new files with content you type directly.

# Create a new file and enter content cat > newfile.txt This is line 1 of my new file. This is line 2. This is line 3. [Press Ctrl+D to finish and save]
$ cat newfile.txt This is line 1 of my new file. This is line 2. This is line 3.
Explanation: The > symbol redirects cat's input (what you type) into a new file. Cat reads from standard input (your keyboard) until you press Ctrl+D (end-of-file marker). Everything you type becomes the content of the new file. This is a quick way to create small files without opening a text editor.
Warning: Using > will overwrite an existing file without warning! Use >> to append instead.
Example 4

Appending Content to an Existing File

The double redirect operator appends data to the end of a file without destroying existing content.

# Append additional lines to an existing file cat >> existingfile.txt Adding this new line to the end. And another line here. [Press Ctrl+D to finish]
$ cat existingfile.txt Original content line 1. Original content line 2. Adding this new line to the end. And another line here.
Explanation: The >> operator appends to a file rather than overwriting it. This is extremely useful for adding entries to log files, configuration files, or any situation where you want to preserve existing content while adding new information.
Real-World Use: Commonly used in scripts to append log entries, add new lines to configuration files, or build cumulative output files from multiple operations.
Example 5

Numbering Lines with -n Option

The -n option adds line numbers to the output, which is helpful for referencing specific lines.

# Display file with line numbers cat -n /etc/fstab
1 # 2 # /etc/fstab 3 # Created by anaconda on Tue Oct 15 14:23:45 2024 4 # 5 UUID=a1b2c3d4-e5f6 / xfs defaults 0 0 6 UUID=b2c3d4e5-f6g7 /boot ext4 defaults 1 2 7 UUID=c3d4e5f6-g7h8 swap swap defaults 0 0 8 /dev/mapper/vg01-data /data ext4 defaults 0 2
Explanation: The -n option numbers every line in the output, including blank lines. The numbers are right-aligned and padded with spaces for consistent formatting. This is invaluable when discussing configuration files with colleagues ("Look at line 7...") or when analyzing files with many entries.
Pro Tip: Use cat -b filename if you want to number only non-blank lines, which can make the numbering more meaningful in files with lots of whitespace.
Example 6

Concatenating Multiple Files into One

This demonstrates cat's original purpose: combining multiple files into a single output file.

# Combine three configuration snippets into one master config cat header.conf database.conf footer.conf > complete.conf # Verify the combined file cat complete.conf
## System Configuration Header ## Generated: 2025-01-15 [database] host = db.example.com port = 3306 user = appuser password = encrypted_password_here ## End of Configuration ## Last modified: 2025-01-15
Explanation: This is cat's core functionality - concatenating (joining) multiple files. Cat reads each file in the order listed and outputs them sequentially. The redirection operator > captures all this output into a single new file. This is perfect for building configuration files from modular pieces or combining log segments.
Real-World Use: Building Apache/Nginx configuration files from reusable components, combining split backup files, or merging code snippets during development.
Example 7

Showing Hidden Characters with -A Option

The -A option reveals special characters that are normally invisible, essential for troubleshooting formatting issues.

# Display file with all special characters visible cat -A problematic_file.txt
First line with normal ending$ Second line^Iwith tab character$ Third line$ $ Fifth line after blank line$ Line with trailing spaces $ Windows line ending^M$
Explanation: The -A option makes invisible characters visible: $ shows line endings, ^I shows tab characters, ^M shows carriage returns (Windows line endings). This is crucial for debugging issues where files "look correct" but don't work - often due to wrong line endings, unexpected tabs, or trailing spaces.
Common Issue: Files edited on Windows and transferred to Linux often have ^M characters (carriage returns) that cause script failures and parsing errors. Cat -A helps identify these problems immediately.
Fix Windows Line Endings: After identifying ^M characters with cat -A, use dos2unix filename to convert them to Unix line endings.
Example 8

Squeezing Multiple Blank Lines

The -s option reduces multiple consecutive blank lines to a single blank line, making output cleaner.

# Display file with squeezed blank lines cat -s messy_file.txt
Section 1: Introduction This is the introduction paragraph. Section 2: Configuration These are the configuration details. Section 3: Examples Here are some examples.
Explanation: The -s (squeeze) option compresses multiple consecutive blank lines into just one blank line. This is useful when viewing files that have excessive whitespace - perhaps from automated generation or careless editing - making the content easier to read without completely removing the section separations.
Pro Tip: Combine with line numbering for even better readability: cat -ns filename gives you numbered lines with squeezed blanks.
Example 9

Using cat with Here Documents

Cat combined with "here documents" is a powerful scripting technique for creating files with variable substitution.

# Create a configuration file with variables SERVER_NAME="web01" IP_ADDRESS="192.168.1.100" PORT="8080" cat > server_config.txt <<EOF Server Configuration ==================== Hostname: $SERVER_NAME IP Address: $IP_ADDRESS Port: $PORT Generated: $(date) EOF # View the created file cat server_config.txt
Server Configuration ==================== Hostname: web01 IP Address: 192.168.1.100 Port: 8080 Generated: Tue Jan 15 14:23:45 EST 2025
Explanation: A "here document" (the <<EOF ... EOF syntax) allows you to feed multiple lines of text to cat as if you were typing them. Shell variables like $SERVER_NAME and command substitutions like $(date) are expanded before cat receives them. This is incredibly useful in scripts for generating configuration files, emails, or reports with dynamic content.
Real-World Use: Automation scripts use this to generate custom configuration files for each server, create HTML reports with current data, or send formatted email notifications with variable content.
Note: Use <<'EOF' (with quotes) if you want to prevent variable expansion and keep everything literal.
Example 10

Reading from Standard Input in Pipelines

Cat can accept input from pipes, making it useful for processing or displaying data from other commands.

# Display sorted user list with line numbers grep "/bin/bash" /etc/passwd | sort | cat -n
1 craig:x:1000:1000:Craig Smith:/home/craig:/bin/bash 2 lynne:x:1001:1001:Lynne Smith:/home/lynne:/bin/bash 3 root:x:0:0:root:/root:/bin/bash 4 sysadmin:x:1002:1002:System Admin:/home/sysadmin:/bin/bash
Explanation: Here, cat receives its input from the pipeline rather than from a file. The grep command finds all users with bash shells, sort arranges them alphabetically, and cat -n adds line numbers to the final output. Using cat at the end of a pipeline is common when you want to number lines or use any of cat's formatting options on the processed data.
Pipeline Alternatives:
  • cat file1 file2 | grep pattern - Search across multiple files
  • cat access.log | awk '{print $1}' | sort | uniq -c - Count unique IPs
  • cat data.txt | tr '[:lower:]' '[:upper:]' - Convert to uppercase
UUOC Award: There's a humorous "Useless Use of Cat" award for unnecessarily using cat when another tool could read the file directly. For example, cat file | grep pattern should be grep pattern file. However, many people prefer the cat style for consistency and readability in complex pipelines.

Additional Information

When NOT to Use cat:

For large files, cat dumps everything to your screen at once. Consider these alternatives:

  • less: For browsing large files with navigation (recommended)
  • more: Simple forward-scrolling viewer
  • head: View just the first N lines
  • tail: View just the last N lines (great for logs)
  • tail -f: Watch a file as it grows (live log monitoring)
Binary Files:

Never use cat to display binary files (executables, images, compressed files). Binary data will produce garbage output and may mess up your terminal settings. If your terminal gets garbled after accidentally catting a binary file, type reset and press Enter to restore it.

Useful cat Combinations:
# Copy file while showing progress cat source.txt | tee destination.txt # Display file with page breaks cat -v document.txt | less # Create backup before viewing cat important.conf | tee backup.conf | less # Count lines, words, and characters cat file.txt | wc # Display with timestamps (using nl for numbers) cat -n logfile.txt | while read num line; do echo "$(date): $line"; done
Shell Scripting with cat:

Cat is frequently used in shell scripts for:

  • Reading configuration files line by line
  • Creating temporary files with specific content
  • Logging script output to files
  • Generating reports by concatenating data sources
  • Building SQL scripts from multiple query files
Security Consideration:

Be cautious when using cat with untrusted files. Files containing special control characters or escape sequences could potentially affect your terminal. Always verify file sources, especially when running with elevated privileges.

Performance Note:

For very large files (gigabytes), cat can consume significant system resources. Consider using streaming tools or processing files in chunks. For example, use split to divide large files or head/tail to sample portions.

Quick Reference Card

Task Command
Display a file cat filename
Display multiple files cat file1 file2 file3
Create a new file cat > newfile.txt
Append to a file cat >> existingfile.txt
Number all lines cat -n filename
Number non-blank lines cat -b filename
Show special characters cat -A filename
Squeeze blank lines cat -s filename
Concatenate files cat file1 file2 > combined.txt
Display with line endings cat -E filename