Use grep -q instead of comparing output
`if [ -n "$(grep x file)" ]` does extra work. `grep -q` returns success/failure directly.
Problem
Capturing grep output to check if it found anything wastes a subshell and an allocation. `grep -q` exits 0 on the first match and 1 on no matches, with no output — perfect for use in `if` directly.
Bad
if [ -n "$(grep error log)" ]; then
alert
fiGood
if grep -q error log; then
alert
fiExplanation
`grep -q` short-circuits at the first match, so it's faster on large files too. Pair with `-s` to suppress error messages about missing files.
When It Matters
if [ -n "$(grep pattern file)" ] reads the whole file, allocates the entire match set in memory, and then throws it away to answer a yes/no question. On a large log or in a loop, that is the difference between a script that finishes in a second and one that takes minutes. It is also wrong in a subtle case: if the matched line is empty or whitespace-only, the command substitution strips it and the test reports no match even though grep found one.
Second Example
Note
grep -q also exits as soon as it matches, which matters when the input is a pipe from a long-running command.
Exceptions
If you actually need the matched text as well as the yes/no answer, capturing it and testing the variable is reasonable — assign once, then test: match=$(grep ... ) and check the exit status with if [ $? -eq 0 ] or by testing the assignment directly. The warning targets the case where the output is captured and immediately discarded.
Faq
Q
Does grep -q suppress errors too?
A
No. It suppresses normal output but still writes errors, such as a missing file, to stderr. Add 2>/dev/null if you want those hidden as well.
Q
How do I test the opposite condition?
A
Put ! in front of the command: if ! grep -q pattern file; then ... fi. There is no need to compare exit codes by hand.
Q
What about testing whether a command produced any output at all?
A
Prefer the command’s own exit status when it has a meaningful one. Only fall back to capturing output when the command reports success regardless of whether it found anything.