Every command exits with a status code. Bash stores the most recent status in $?, where zero means success.

Program

Play the script to see a missing file test set a nonzero status.

exit_status.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

path="/tmp/report.txt"
[[ -f "$path" ]]
status=$?
echo "status=$status"
  1. path ← /tmp/report.txt

    3path="/tmp/report.txt"4[[ -f "$path" ]]
    values this step/tmp/report.txtpath
  2. test ← false, $? ← 1

    3path="/tmp/report.txt"4[[ -f "$path" ]]5status=$?
    values this stepfalsetest1$?/tmp/report.txtpath
  3. status ← 1

    4[[ -f "$path" ]]5status=$?6echo "status=$status"
    values this step1status1$?
  4. echo "status=$status"

    5status=$?6echo "status=$status"
    outputstatus=1
    values this step1status

Follow the Status

  1. path names the file the script wants to check.
  2. [[ -f "$path" ]] asks whether that file exists.
  3. Bash stores the command result in $?.
  4. The script copies $? into status before another command changes it. | Status | Meaning | | --- | --- | | 0 | the test succeeded | | nonzero | the test failed |
exit status A command reports success or failure with a small integer status code.
test command `[[ ... ]]` evaluates a condition and sets an exit status.

Exercise: exit_status.sh

Check whether a path exists, save $?, and print one message for 0 and another for nonzero