Skip to content

Files

Latest commit

 

History

History
35 lines (23 loc) · 855 Bytes

SC2143.md

File metadata and controls

35 lines (23 loc) · 855 Bytes

Pattern: Missing use of grep -q

Issue: -

Description

Example of incorrect code:

if [ "$(find . | grep 'IMG[0-9]')" ]
then
  echo "Images found"
fi

The problematic code has to iterate the entire directory and read all matching lines into memory before making a decision.

Example of correct code:

if find . | grep -q 'IMG[0-9]'
then
  echo "Images found"
fi

The correct code is cleaner and stops at the first matching line, avoiding both iterating the rest of the directory and reading data into memory.

Exceptions

The pipefail bash option may interfere with this rewrite, since the if will now in effect be evaluating the statuses of all commands instead of just the last one. Be careful using them together.

Further Reading