Consider using `grep -c`SH-2126
Consider using grep -c instead of grep | wc.
This is purely a stylistic issue. grep can count lines without piping to wc.
Often this number is only used to see whether there are matches (i.e. == 0).
In these cases it's clearer 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 and always return success unless a directive like set -o pipefail is present.
By instead writing foo | grep -c bar, grep will exit with a non-zero value when there are no matches.
This is generally desirable (see below), but may require handling when used with set -e.
Bad Practice
grep foo | wc -l
Recommended:
grep -c foo
For Multiple Files, instead of:
grep foo *.log | wc -l
You can pipe all the file contents into grep (passing the files directly to grep causes -c to print each file's count separately, rather than the total):
cat *.log | grep foo -c
Exceptions
If you find piping to wc is clearer in a given situation it's fine to ignore this issue.