mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2026 (markdown)
24
SC2026.md
Normal file
24
SC2026.md
Normal file
@@ -0,0 +1,24 @@
|
||||
## Consider using grep -c instead of grep|wc.
|
||||
|
||||
### Problematic code:
|
||||
|
||||
grep foo | wc -l
|
||||
|
||||
### Correct code:
|
||||
|
||||
grep -c foo
|
||||
|
||||
### Rationale:
|
||||
|
||||
This is purely a stylistic 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
|
||||
|
||||
### Contraindications
|
||||
|
||||
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.
|
Reference in New Issue
Block a user