Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Exit Codes and Conditionals  ›  Lesson

Exit Codes: $? and exit

$? 12 minEvery command ends with an exit status from 0 to 255, where 0 means success and anything else means failure, available in $? right afterwards and set by a script with exit.

Exit Codes: $? and exit

tar fails because the disk is full, prints an error that scrolls away, and backup.sh cheerfully echoes "Backup done". A script cannot read error messages like you do. It reads something simpler: a number every command leaves behind when it finishes.

The rule

Zero means success; any other number, 1 to 255, means failure.

Every command ends with an exit status. Bash keeps the most recent one in $?:

ls ~/notes     ; echo $?     # 0   the folder exists
ls ~/nothing   ; echo $?     # a non-zero number, such as 1 or 2

This is the reverse of many programming languages, where 0 means false. In the shell, 0 is the one way to succeed and every other number is a different way to fail. Some common ones:

Status Usual meaning
0 success
1 general failure
2 misused the command (bad options or arguments)
126 found but not executable
127 command not found
130 stopped by Ctrl-C (128 + signal 2)

A script sets its own status with exit:

tar -czf "$archive" "$src"
status=$?
echo "tar finished with status $status"
exit "$status"

If a script has no exit, its status is that of the last command it ran. Values wrap around at 256, so exit 256 reports 0 and exit 300 reports 44. Keep to 0 to 255.

The shortcut

$? is a one-shot reading: catch it on the very next line or lose it. Every command, even echo, replaces it. So the habit is run, save, use: status=$? straight after the command you care about.

Why the second echo prints 0Step 1 of 4
  1. Run the failing command

    ls /nope fails and sets $? to a non-zero value.

Drills

Answer fast — trust the rule.

quick drill

What does false; echo $? print?

quick drill

You run ls /nope, then echo $?, then echo $? again. What does the second echo print?

quick drill

You mistype a command, lss, and press Enter. What is $? now?

quick drill

A script ends with exit 300. What status does its caller see?

quick drill

A script has no exit line, and its last command is grep finding no match. What is the script's status?

Remember

  • Zero means success; 1 to 255 means failure.
  • $? is one-shot: run, save, use.
  • A script without exit returns its last command's status; end with exit on purpose.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainDid tar succeed?

After the tar line in backup.sh, the script should report tar's exit status and then finish with that same status. Write the lines and explain what 0 and non-zero mean, why the status must be saved right away, and what the script's status would be with no exit line at all.