SC2126: Use grep -c Instead of grep | wc -l

Replace grep | wc -l with the more efficient grep -c. Learn about related pipeline simplifications for shell scripts.

ShellCheck Patterns

Detailed Explanation

grep -c vs grep | wc -l

A common shell scripting habit is piping grep output to wc -l to count matching lines. This is unnecessary because grep has a built-in -c (count) flag.

The Anti-Pattern

# Unnecessary pipeline
error_count=$(grep "ERROR" logfile.txt | wc -l)

The Fix

# Built-in count
error_count=$(grep -c "ERROR" logfile.txt)

Why -c Is Better

  1. One process instead of two: Eliminates the pipe and wc process
  2. Faster: grep stops tracking match content when only counting
  3. Simpler: Easier to read and understand

Important Difference

grep -c counts lines, not matches. If a line matches multiple times, it is still counted once:

echo "error error error" | grep -c "error"   # Output: 1
echo "error error error" | grep -o "error" | wc -l  # Output: 3

If you need to count individual matches (not lines), grep -o | wc -l is the correct approach.

Related Pipeline Simplifications

Inefficient Efficient
`grep pattern file wc -l`
`cat file grep pattern`
`grep pattern file head -1`
`grep -v pattern grep -c ""`
`sort file uniq`
`cat file sort`

Checking If Any Match Exists

# BAD: Count and compare
if [ $(grep -c "ERROR" log.txt) -gt 0 ]; then

# GOOD: Use grep -q (quiet mode, exits on first match)
if grep -q "ERROR" log.txt; then
  echo "Errors found"
fi

grep -q is the most efficient way to check for the existence of a pattern — it stops reading after the first match.

Use Case

Log analysis scripts, monitoring tools, and any automation that counts occurrences in files. Also useful for code reviews to improve script efficiency and readability.

Try It — Shell Script Linter

Open full tool