SC2002: Useless Cat — Unnecessary Use of cat in Pipelines

Eliminate unnecessary cat commands in shell pipelines. Learn efficient alternatives using input redirection and command arguments.

Anti-Patterns

Detailed Explanation

The Useless Use of Cat

"Useless Use of Cat" (UUOC) is a well-known shell scripting anti-pattern where cat is used unnecessarily to pipe file contents into a command that can read files directly.

The Anti-Pattern

# BAD: Useless cat
cat file.txt | grep "error"
cat file.txt | wc -l
cat file.txt | sort | uniq
cat config.yml | head -20

The Fix

Most commands can read files directly, either as arguments or via input redirection:

# GOOD: Direct file argument
grep "error" file.txt
wc -l file.txt
sort file.txt | uniq
head -20 config.yml

# GOOD: Input redirection
grep "error" < file.txt
wc -l < file.txt
sort < file.txt | uniq

Why It Matters

  1. Performance: Extra process and pipe for no benefit
  2. Error handling: If the file doesn't exist, cat's error message gets mixed with the pipeline's output
  3. Signals: Adds an unnecessary process to the pipeline

Input Redirection vs Arguments

# Argument: filename appears in output
wc -l file.txt
# Output: 42 file.txt

# Redirection: no filename in output
wc -l < file.txt
# Output: 42

When cat IS Useful

# Concatenating multiple files (cat's original purpose)
cat header.txt body.txt footer.txt > page.html

# Reading from stdin in a script
cat  # Read from stdin and write to stdout

# Displaying file content to terminal
cat file.txt  # Legitimate use

# Using cat with special options
cat -n file.txt      # Number lines
cat -A file.txt      # Show non-printing characters

Advanced: Process Substitution Alternative

# Instead of: cat <(command1) <(command2) | sort
# Use: sort <(command1) <(command2)

# Comparing two command outputs
diff <(sort file1.txt) <(sort file2.txt)

Use Case

Code review, script optimization, and style enforcement. While not a functional bug, eliminating useless cat improves readability, reduces process overhead, and signals shell scripting competence.

Try It — Shell Script Linter

Open full tool