Terminal · foundation

Exit status

An exit status is a small integer produced when a command or pipeline completes; zero conventionally means success and nonzero meanings are defined by that command's interface.

Why it matters

Shell control flow and automation depend on status, so collapsing every nonzero value into the word failure can turn expected results into false alarms.

Mental model

How to reason about exit status

The shell reduces a completed command or pipeline to one compact outcome code. An external process's termination status is one source; built-ins, functions, and compound commands also produce shell statuses.

Analogy

It is a machine-readable outcome label on a completed job, not the detailed report; logs and stderr provide explanation while the code supports branching.

Examples

See the boundary, not just the happy path

Worked example · Inspect the previous status

test -f config.json; printf '%s\n' "$?"

The special parameter $? contains the status of the most recently completed foreground pipeline, so it must be read before another command replaces it.

Worked example · Three-way grep outcome

grep -q needle haystack.txt

grep documents 0 for a selected line, 1 for no selected line, and greater than 1 for an error; status 1 is an expected negative result.

Useful contrast · Diagnostic text is separate

tool 2> error.log

Redirecting stderr changes where diagnostic bytes go but does not by itself alter the process's exit status.

Common mistakes

Misconceptions to remove early

Treating nonzero as one undifferentiated failure

Commands can reserve statuses for false predicates, partial differences, usage errors, or runtime errors; automation should use documented meanings.

Reading $? too late

Every intervening command or pipeline updates the shell's last status, so capture it immediately when later logic needs it.

Quick check

Can you predict the result?

1. What does grep status 1 mean when no other error occurred?
  • No input line was selected
  • grep could not start
  • The file was modified
Answer: No input line was selected
2. Why is stderr text not a substitute for exit status in automation?
Answer: Exit status is the defined machine-readable outcome, while stderr is an unstructured diagnostic stream that may be empty, localized, or informational.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster