How to Use the cat Command in Linux?


The Ultimate Guide to the cat Command in Linux

Introduction

The cat command, short for “concatenate,” is one of the most fundamental and frequently used commands in Linux. It reads files sequentially and outputs their contents to the terminal. Despite its simplicity, cat is incredibly versatile—whether you’re viewing files, combining them, or piping their contents to other commands. However, it’s often misused when simpler alternatives exist [1].

Usage

The basic syntax of cat is:

cat [OPTIONS] [FILE]...

Key Options:

  • -n or --number: Number all output lines (including blank ones).
  • -b or --number-nonblank: Number only non-empty lines.
  • -s or --squeeze-blank: Suppress repeated empty lines.
  • -T or --show-tabs: Display tabs as ^I (useful for debugging).
  • -E or --show-ends: Show $ at the end of each line.

Common Use Cases:

  1. View a File:
    cat filename.txt
  2. Combine Multiple Files:
    cat file1.txt file2.txt > merged.txt

Stop Abusing Cats !

A common anti-pattern is using cat unnecessarily. For example:

cat file.txt | grep "pattern"  # Bad: Extra process
grep "pattern" < file.txt      # Better: Direct redirection

Why? cat spawns an additional process, which is inefficient. Using shell redirection (< or pipes) directly is cleaner and faster.

Examples

1. Display Line Numbers:

cat -n logfile.txt

2. Show Non-Printable Characters:

cat -v binaryfile

3. Merge Files:

cat part1.txt part2.txt > complete.txt

Conclusion

cat is a powerful tool, but use it wisely. Avoid redundant calls and embrace direct redirection where possible. Happy Linux hacking!

See Also