grep Exit Codes: 0, 1, and 2 in Pipelines
grep returns 0 when at least one line matched, 1 when none matched, and 2 when it hit an error.
The exit code is the part of grep that breaks pipelines most often. Knowing the three values lets you assert on output without accidentally failing a job.
What it does
grep signals its result through the exit status, not only through printed lines. 0 means a match was found, 1 means the search completed but found nothing, and 2 means an error occurred (a missing file, a bad pattern, a permission problem). Many shells run jobs under set -e, which aborts on any non-zero exit.
Common usage
# assert a pattern is present (fails the step if absent)
grep "BUILD SUCCESS" build.log
# tolerate no match without failing set -e
grep "WARN" build.log || true
# branch on the result explicitly
if grep -q "ERROR" build.log; then echo "found errors"; fiOptions
| Exit code | Meaning |
|---|---|
| 0 | At least one line matched |
| 1 | No lines matched (not an error) |
| 2 | An error occurred (bad file, bad regex, etc.) |
| -q / --quiet | Suppress output; still sets the exit code |
| -s / --no-messages | Suppress error messages about unreadable files |
In CI
Decide per call whether a non-match is success or failure. To require a pattern, let a bare grep fail the step. To tolerate its absence, append || true. To act on presence without failing, use if grep -q ...; then. Under set -o pipefail, a grep inside a pipe can also surface its exit 1.
Common errors in CI
A step that "passes locally but fails in CI" often runs a grep that finds nothing under set -e. The fix is || true or restructuring with if grep -q. Exit 2 is different: it is a real error such as "No such file or directory" or "invalid option", and || true will mask a genuine bug, so investigate it instead of swallowing it.