ch00/l03

Exit status and first failure reading

Use exit status and stderr as evidence instead of blindly retrying.

echo $? 15 min read, 20 min lab beginner

Every command exits with a status. Zero usually means success; non-zero usually means failure. Error text tells you what failed: permission, missing file, bad option, network refusal, or a command not found. Retrying before reading the failure burns time.

In the field

A setup script says it failed. You need the immediate failure class before changing anything.

Worked command

$ test -f /etc/passwd$ echo $?0$ test -f /no/such/file$ echo $?1$ ls /rootls: cannot open directory '/root': Permission denied
Anti-pattern

Do not treat every non-zero as the same problem. Permission denied, no such file, and invalid option need different next steps.

Safer pattern

Read the message, check the status, and classify the failure before acting.

Knowledge check

A command finishes and `echo $?` prints 0. What have you actually proven?

  • A The command produced the output you intended
  • B The command reported success; the real effect still needs checking
  • C Nothing, since 0 conventionally signals failure
  • D Both stdout and stderr were empty
Show the answer

Correct: B. The command reported success; the real effect still needs checking

Why

Exit 0 means the program reported success by its own convention, not that the intended state change occurred, so you still verify the effect. Assuming 0 equals the right result skips the confirmation that catches commands that succeed at doing the wrong thing.

Practice checklist

  1. Run one command that succeeds and one that fails in a throwaway directory.
  2. Record the stderr text and exit status.
  3. Write the next least-invasive check for each failure.

Deliverable evidence

  • Two command transcripts with exit status.
  • A short failure-classification note.
Teaching diagramch00 · mental model
read state, then act, then read the result1. prompt statewhoami / hostnamepwd / $SHELL2. command shapecmd -opts argsverify: man / --help3. exit statusecho $?0 ok / non-zero stopread stderr firstnon-zero?prompt theme shows, it does not prove

shows: The chapter's operator loop: read prompt state, parse the command into executable/options/arguments and verify it, run it, then read exit status and stderr before the next move.

does not prove: It does not prove a zero exit status means the intended effect happened, nor that the prompt's displayed host, path, or privilege are accurate; both must be confirmed with commands when consequences matter.

Memorize this

Commit these to memory, then drill them until recall is automatic.

echo $?0 means successnon-zero means inspect
Recall practice · Output -> explanation

cue Meaning: command exited with a non-zero status

show recall target

Failure reported; read stderr to classify it (permission, missing file, bad option, network) before retrying