How to Use cat Command in Linux: Syntax and Examples
The
cat command in Linux is used to display the contents of files, combine multiple files, or create new files by outputting text. You run it by typing cat [options] [file_names] in the terminal to see or manipulate file content quickly.Syntax
The basic syntax of the cat command is:
cat [options] [file_names]
Here, file_names are the files you want to display or combine. Options modify how cat behaves, like showing line numbers or handling special characters.
bash
cat [options] [file_names]
Example
This example shows how to display the content of a file named example.txt and how to combine two files into a new file.
bash
cat example.txt cat file1.txt file2.txt > combined.txt
Output
Hello from example.txt!
# After combining file1.txt and file2.txt, the new file combined.txt contains the contents of both files concatenated.
Common Pitfalls
One common mistake is overwriting files unintentionally when using cat with redirection. For example, using cat file1.txt > file1.txt will erase the file before reading it.
Also, forgetting to specify a file will cause cat to wait for input from the keyboard until you press Ctrl+D.
bash
cat file1.txt > file1.txt # Wrong: overwrites file before reading
cat file1.txt >> file1.txt # Also problematic: appends file to itself
# Correct way to append file2.txt to file1.txt
cat file2.txt >> file1.txtQuick Reference
| Option | Description |
|---|---|
| -n | Show line numbers for all lines |
| -b | Show line numbers only for non-empty lines |
| -s | Squeeze multiple blank lines into one |
| -E | Display $ at the end of each line |
| -T | Show tabs as ^I |
Key Takeaways
Use
cat [file] to quickly display file contents in the terminal.Combine files by listing multiple files and redirecting output:
cat file1 file2 > newfile.Avoid overwriting files by not redirecting output to the same file you are reading.
Use options like
-n to add line numbers for easier reading.If no file is specified,
cat reads from keyboard input until Ctrl+D is pressed.