Skip to content
Latchkey

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

Terminal
# 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"; fi

Options

Exit codeMeaning
0At least one line matched
1No lines matched (not an error)
2An error occurred (bad file, bad regex, etc.)
-q / --quietSuppress output; still sets the exit code
-s / --no-messagesSuppress 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.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →