Linux Exit Status and Command Errors
Success is a number, not a message
When a foreground command completes, Bash records its status. Zero normally means success; a nonzero value reports a different outcome whose exact meaning belongs to that command. $? expands to the most recent foreground pipeline’s status. For these single-command examples it is the status of the command just run. Run the following in a normal Bash session without automatic exit-on-error enabled.
Neither true nor false prints a message. The numbers come from printf. true reports success and false returns 1. Reading $? immediately matters because the next command normally replaces the status.
Treat the number as a result supplied to the shell, not as the text that the command prints. The printing command itself also finishes with a status, so reading the status a second time without rerunning the original command can describe the printing command instead.
A real error in a read-only command
For file examples, open a terminal in the supplied lab-fixtures/command-basics/sample-data folder (or use a file manager’s Open in Terminal action). It contains notes.txt, Notes.txt, daily report.txt, .hidden and -draft. The examples only read these files. The exact display order depends on locale; the examples below assume the C locale and GNU ls. The file missing-example.txt is deliberately absent.
GNU ls reports a diagnostic (normally on standard error, a separate output stream) and exits with status 2 in this case. The following printf prints the number to normal output. Other ls implementations or situations may differ. A nonzero status need not imply a printed error; false is a counterexample.
Missing commands and overwritten status
bytemind_missing_command_71printf '%s\n' "$?"In the clean Bash lab, a command name that cannot be found returns 127. A command that is found but cannot be executed conventionally returns 126 in Bash. Custom command-not-found handlers can alter the outcome. Do not assume that every nonzero code means the same error.
The most recent command is true, so the earlier 1 has been replaced by 0. A successful printf after a failure likewise does not repair the failed operation. Later shell lessons use status checks to decide what to do next.
Practice
Run true and read its status immediately; repeat for false. Predict what happens if you run pwd in between. Explain why a nonzero status and a diagnostic are different pieces of evidence.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exit status and errors — Knowledge Check
Apply the command-line concept in a safe beginner lab.
What does true normally return?
What is the immediate status after false?
After false, then true, what does $? report?
What does Bash usually return when a command name is not found?
Which statement about a nonzero status is correct?