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
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
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
cat /var/log/messages.* will display all files matching that pattern in alphabetical order.
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]
> 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.
> will overwrite an existing file without warning! Use >> to append instead.
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]
>> 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.
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
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.
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
> captures all this output into a single new file. This is perfect for building configuration files from modular pieces or combining log segments.
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
$ 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.
^M characters (carriage returns) that cause script failures and parsing errors. Cat -A helps identify these problems immediately.
dos2unix filename to convert them to Unix line endings.
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
cat -ns filename gives you numbered lines with squeezed blanks.
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
<<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.
<<'EOF' (with quotes) if you want to prevent variable expansion and keep everything literal.
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
cat file1 file2 | grep pattern- Search across multiple filescat access.log | awk '{print $1}' | sort | uniq -c- Count unique IPscat data.txt | tr '[:lower:]' '[:upper:]'- Convert to uppercase
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
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)
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.
# 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
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
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.
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 |