Decisions and Status
Exit Status
Command Results
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"
path ← /tmp/report.txt
3path="/tmp/report.txt"4[[ -f "$path" ]]values this step/tmp/report.txtpathtest ← false, $? ← 1
3path="/tmp/report.txt"4[[ -f "$path" ]]5status=$?values this stepfalsetest1$?/tmp/report.txtpathstatus ← 1
4[[ -f "$path" ]]5status=$?6echo "status=$status"values this step1status1$?echo "status=$status"
5status=$?6echo "status=$status"outputstatus=1values this step1status
Follow the Status
pathnames the file the script wants to check.[[ -f "$path" ]]asks whether that file exists.- Bash stores the command result in
$?. - The script copies
$?intostatusbefore 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