BASH / CHAPTER 03
Exit status and conditional work
BeginnerUse command success as control flow instead of guessing from output.
By the end of this chapter
- Interpret zero and nonzero exit statuses
- Use if around the command being checked
- Trace arithmetic loops without off-by-one errors
The idea
In Bash, a command’s exit status communicates success or failure separately from the text it prints. Zero conventionally indicates success; nonzero indicates another outcome that the command documents. An if statement runs a command and selects its branch from that status. This differs from treating a printed word such as false as a boolean value.
Test the command directly when possible, because running another command overwrites the status stored in $?. Bash’s double-bracket conditional provides string and file tests, while arithmetic contexts support numeric comparisons and calculations. Choose the test from the data’s meaning and quote text where needed. In a loop, state the inclusive or exclusive endpoint explicitly, then check empty and one-iteration cases before relying on a larger example.
#!/usr/bin/env bash
if false; then
printf 'success\n'
else
printf 'failure\n'
fi
total=0
for ((i=1; i<=3; i++)); do total=$((total+i)); done
printf '%s\n' "$total"failure 6
false returns a nonzero status, selecting else. The arithmetic loop includes one, two, and three, producing a total of six.
Try it yourself
Write a condition that prints "ready" only when a nonempty name has been supplied.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING