As a lifelong Linux user and command line enthusiast, cat is easily one of my most used and beloved commands. Mastering cat is an essential skill for anyone who wants to harness the true power of the Linux terminal.
In this comprehensive guide, I‘ll share with you all my insights and expertise for getting the most out of cat, whether you‘re a beginner or a grizzled Linux veteran. When we‘re done, you‘ll have a deep understanding of how to wield cat like a pro!
What Exactly Does the Cat Command Do?
Before we dive in, let‘s briefly overview what cat does under the hood.
At its core, cat (short for concatenate) is used to output and combine the contents of files. According to the Linux man pages, it:
- Concatenates files and prints them to the standard output (usually your terminal)
- Can combine multiple files as well as data from standard input
- Does not alter the contents or metadata of the original files
So in a nutshell, cat lets you view, merge, and redirect textual data streams without modifying the source. It‘s one of the most versatile tools for handling files and streams in the Linux toolbox.
Personally, I think of cat as the Linux equivalent of duct tape – it‘s simple and straightforward, but can be used in a million different ways. Learning cat deeply will supercharge your terminal productivity.
Cat Command Syntax and Options
The basic syntax of cat is straightforward:
cat [options] [file...]
Let‘s break this down:
cat– Invoke the cat command[options]– Optional flags that change behavior[file...]– One or more input files to read
Calling cat with no arguments will read from standard input. This allows you to pipe data from other commands into cat.
Some examples of cat syntax:
cat myfile.txt # Print myfile.txt contents
cat file1 file2 # Print two files together
cat < input.txt # Read stdin from input.txt instead of arg
cat # Read from stdin
The real workhorse of cat is its options – these unlock some very useful capabilities. Here are some of my frequently used ones:
| Option | Description |
|---|---|
-A |
Print non-printable characters |
-b |
Number non-empty lines |
-n |
Number all lines |
-s |
Squeeze consecutive blank lines |
-T |
Show tabs as ^I |
-v |
Show non-printable chars as escape codes |
You can combine options together for extra flexibility e.g. cat -bns file. Mastering these options will give you finesse in handling text outputs.
Now that we‘ve covered the basics, let me walk you through some everyday examples of using cat.
Quickly Viewing and Concatenating Files
The most common use case for cat is simply viewing the contents of text files right in your terminal:
# View the contents of access.log
cat access.log
# View multiple files
cat file1.txt file2.txt
This lets you quickly peek at and scroll through file contents without opening a text editor.
Often I‘ll use cat to preview config files across servers:
# Check nginx configs on multiple servers
cat /etc/nginx/nginx.conf
cat /etc/nginx/sites-enabled/default
You can also use cat to quickly combine files together:
# Combine two CSS files
cat style1.css style2.css > combined.css
Or append to an existing file:
cat error_log.txt >> master_log.txt
These are the simple everyday use cases for concatenating and printing files with cat. But the real power comes from redirecting input and output…
Harnessing Input/Output Redirection
In Linux, input and output redirection allow you to control where cat receives data from and sends it to. This unlocks new ways to manipulate and transform text streams.
For example, redirecting output with > writes cat data to a file instead of the terminal:
cat file.txt > output.txt
The >> appends instead of overwriting:
cat file.txt >> existing.txt
You can use this to combine files:
cat file1.txt file2.txt > combined.txt
Input redirection with < forces cat to read from the given file rather than arguments:
cat < input.txt
This lets you redirect streams from other commands:
ls -l | cat < input.txt
In this way, cat becomes the ultimate duct tape for wrangling text streams – you can glue inputs and outputs from many different sources.
As an experienced Linux user, I can‘t emphasize enough how important it is to master input/output redirection. It will supercharge your shell scripting and make complex text processing tasks easy.
Next, let me show you how redirection enables some really useful cat tricks…
Useful Tricks with Redirection
Beyond basic file handling, redirection unlocks some really cool uses for cat that I employ regularly:
1. Creating New Files
You can use cat with redirection to generate new files on the fly:
# Create newFile.txt
cat > newFile.txt
Then type in your content, and press CTRL-D when done.
This comes in really handy when I need to quickly spawn some config files or code snippets:
cat > nginx.reverseproxy.conf
Much faster than opening up a text editor!
2. Append to Existing Files
Similarly, you can append content to existing files without opening them:
cat >> todo.txt
Then add your new list items, press enter a few times, and CTRL-D to append.
3. Read from Standard Input
When called without arguments, cat will read from standard input. This allows you to pipe data between programs:
ls -l | cat
The directory listing gets passed to cat via the pipe.
You can also explicitly read stdin with a hyphen (-):
cat -
This technique is invaluable in shell scripts when you need to accept piped data from another program.
4. Number Lines
Want to quickly count lines in a file? Use cat -n:
cat -n file.txt
It will number each line in the output – the last one shows the total.
5. View Invisible Characters
Pass -v to display non-printing characters as escape codes:
cat -v file.txt
This helps reveal things like tabs and newlines.
6. Squeeze Blank Lines
The -s flag condenses consecutive empty lines into a single line:
cat -s file.txt
This cleans up text spacing if you have too many newlines.
These handy tricks showcase the versatility of cat for both text processing and file handling. With just a few keystrokes, you can wrangle data streams like a pro.
Creating and Concatenating Files
A common use case for cat is combining multiple files into a new file, or appending to an existing one.
For instance, to concatenate file1.txt and file2.txt into a new file called combined.txt:
cat file1.txt file2.txt > combined.txt
To append them instead to master_file.txt:
cat file1.txt file2.txt >> master_file.txt
You can merge any number of files this way:
cat file1.txt file2.txt file3.txt > merged_file.txt
Some other examples:
# Concat all .txt files
cat *.txt > alltext.txt
# Grep through .log files and combine matches
grep ERROR *.log > errors.log
These allow you to efficiently wrangle and combine data without tedious manual editing.
According to my Linux administrator friends, they‘ll frequently use constructs like this when managing log files across servers:
# Collect sshd logs
cat /var/log/sshd.log* > sshd_combined.log
# Merge Apache access logs
cat /var/log/apache2/access.log* > combined_access.log
So don‘t underestimate the power of cat for combining files!
Reading from Standard Input
When called without any file arguments, cat will read from standard input (stdin) rather than a file.
This allows you to pipe data from another command into cat:
# Pipe ls output into cat
ls -l | cat
The directory listing gets passed to cat via the pipe.
You can also explicitly read from stdin using a hyphen (-):
cat -
This is useful in shell scripts when you need to accept piped data from another program:
#!/bin/bash
cat -
# Now pipe data:
# echo "text" | myscript.sh
Some other examples:
# Pipe curl output
curl -s https://www.example.com | cat
# Pipe output of find
find . -type f | cat
In this way cat acts as a generic consumer of textual data streams. Mastering stdin handling is a key skill for shell scripting.
Viewing Command Outputs
Another handy use case is displaying the full output of terminal commands.
For example, you can use cat to show the full contents of a long directory listing:
ls -l | cat
Or comparing full config files across servers:
# Show nginx config from multiple servers
cat /etc/nginx/nginx.conf
cat /etc/nginx/sites-enabled/default
You can also cat the outputs of text processing commands like grep and awk to review matches:
grep ERROR logs.txt | cat
awk ‘{print $2}‘ data.csv | cat
This allows you to conveniently inspect command results in the terminal.
Debugging Shell Scripts
When writing shell scripts, cat is indispensable for printing debug information.
Just sprinkle cat statements throughout your script:
#!/bin/bash
name="John"
cat "Hello $name"
# More script logic...
if [ $name == "John" ]; then
cat "Name is John"
fi
cat "End of script"
This lets you monitor variables, outputs, and program flow without having to constantly write to log files.
Debugging tip: You can highlight cat output in color by piping to ccze -A:
cat "Error occurred" | ccze -A
This really makes debug text pop out.
Viewing File Differences
Another handy trick is using cat to show diffs between files.
Just pipe the output of diff into cat:
diff file1.txt file2.txt | cat
This displays the full differentiation rather than just a summary.
You can also pass through ccze to colorize the output:
diff file1.txt file2.txt | ccze -A | cat
This makes it really easy to spot differences between files.
Counting Lines
You can leverage cat to quickly count the number of lines in a file.
Just use the -n flag to number all output lines:
cat -n file.txt
The last line printed will display the total line count.
This comes in handy when trying to determine size for log rotation, validation checks, and other tasks.
Viewing Non-Printable Characters
The -v or -A flags make cat display non-printable characters like tabs, newlines, and escape codes.
For example:
cat -v file.txt
This renders newlines as $, tabs as ^I, and other odd chars as escaped values like \x0b.
It‘s invaluable when dealing with files that may have weird hidden characters messing up formatting or scripts.
Removing Extra Blank Lines
The -s flag condenses consecutive empty lines in the output:
cat -s file.txt
This can help clean up text spacing if you have too many repeating newlines.
Alternative Tools
While cat is used ubiquitously, there are some alternative tools that offer more options:
less– Allows scrolling, search, line numbershead/tail– Display first or last N linessed– Advanced text transformationawk– Powerful text processing
In particular, I suggest learning less in conjunction with cat – it enables easy interactive viewing of long text outputs from cat.
But overall cat remains a versatile workhorse for file handling that I use daily.
Putting It All Together: A Sample Shell Script Using Cat
To tie together everything we‘ve covered, here is an example shell script that exercises some common cat usage patterns:
#!/bin/bash
# Print info
cat "Beginning script..."
# Concatenate files
cat file1.txt file2.txt > combined.txt
# Number lines
cat -n combined.txt
# Output variables
name="John"
cat "Hello $name"
# Read stdin
cat -
# Debug printing
cat "Reached end of script"
This shows how cat can be woven into scripts to handle printing, file merging, debugging etc. Mastering these little cat snippets will make you a much more effective shell scripter.
Summary: Mastering the Cat Command
After reading this guide, you should have a very deep understanding of how to use cat effectively. To recap:
- Use
catto print, concatenate, and redirect textual data streams - Harness input/output redirection to transform and pipe data
- Create, append, and combine files on the fly
- Access stdin to read piped data from other programs
- Insert
catdebug printing in scripts - Employ options like
-nand-vfor advanced text manipulation
While a simple tool on the surface, cat offers immense power under the hood. It truly is the duct tape of Linux system administration.
I hope all these tips and examples provide a smooth onramp to mastering cat. Now get out there, try some cat commands yourself, and let me know what cool tricks you come up with! Happy catting!