Pattern: Use of grep|wc
instead of grep -c
Issue: -
grep
can count lines without piping to wc
.
Note that in many cases, this number is only used to see whether there are matches (i.e. == 0
). In these cases, it's better and more efficient to use grep -q
and check its exit status:
if grep -q pattern file
then
echo "The file contains the pattern"
fi
Also note that in foo | grep bar | wc -l
, wc will mask the exit code of grep by default (i.e. without set -o pipefail
), and always return success. If replacing with foo | grep -c bar
, grep will exit non-zero when the count is 0. This is convenient for conditional statements but may require handling when used with set -e
.
Example of incorrect code:
grep foo | wc -l
Example of correct code:
grep -c foo
If you e.g. want to count characters instead of lines, and you actually care about the number and not just whether it's greater than 0, you can ignore this error.