Bash Control Structures
Shell Control Flow: Choosing and Repeating Commands
Shell control flow determines which commands run, which are skipped, and which repeat. You use it to choose a recovery action, process a list of jobs, or stop when a condition changes. These examples use Bash syntax. The focus is execution order; the conditions themselves are supplied rather than developed as a separate topic.
Command status controls decisions
Control flow is the order in which a program executes commands. In Bash, many decisions depend on an exit status, the integer a command returns to report its outcome. Status zero indicates success; a nonzero status indicates an unsuccessful outcome, whose meaning depends on the command.
The commands true and false return zero and one, respectively. A condition does not need to print anything: the shell tests its status, not its displayed output. If a condition contains several sequential commands, its final command supplies the status used for the decision.
For example, (( n < 3 )) succeeds when the current value of n is below three. You can follow the control flow using that stated condition without studying additional expression syntax.
Select a route
An if construct runs its condition first. If that condition succeeds, Bash runs the then branch and skips the remaining branches. Otherwise, it tries each elif condition in order. An optional else handles the situation where no condition succeeds. The keyword fi closes the construct.
if false; then
printf 'primary route\n'
elif true; then
printf 'backup route\n'
else
printf 'no route\n'
fiHere, only the backup message prints. An if chain chooses at most one branch, even when several possible conditions could succeed.
A case construct selects a branch by matching one supplied word against alternatives. Each ordinary branch ends with ;;, and esac closes the construct. The final * branch provides a fallback match.
case stop in
start) printf 'starting\n' ;;
stop) printf 'stopping\n' ;;
*) printf 'unknown action\n' ;;
esacThis prints the stopping message. Pattern construction is a separate topic; here, concentrate on choosing a branch and then leaving the construct.
Repeat commands and leave loops
A loop body is the group of commands between do and done. Each iteration executes that body unless a control command changes the route.
Construct | What determines repetition? | When can the body be skipped entirely? |
|---|---|---|
for item in list | One pass for each listed item | When the resulting list is empty |
while command | Repeat while the condition succeeds | When the first condition returns nonzero |
until command | Repeat while the condition does not succeed | When the first condition returns zero |
A list-based for loop assigns successive items to its variable. Bash also supports a counted arithmetic form, for (( initialization; condition; update )). That form initializes once, tests before each pass, and updates after each normally completed pass.
Plain break exits the innermost loop. Plain continue skips the remainder of its current pass. In while and until, execution returns to the condition; in an arithmetic for, the update runs before the next test. A positive argument, such as break 2, applies the command across that many enclosing loop levels.
What to remember
- Command status zero means the condition succeeds.
- An if chain chooses at most one branch; ordinary case branches end with ;;.
- while repeats on success; until repeats on non-success.
- break leaves a loop; continue skips the rest of a pass.
- Check the next test and update before deciding whether a loop terminates.
Example: Stop a Payload Batch at Its Boundary
Example: A transfer service examines queued payloads in the order shown below. Each size is an exact number of megabytes, abbreviated MB. A zero-sized payload is skipped, and the first payload larger than 12 MB ends the batch before it is added. Assume ordinary Bash execution with automatic exit on an unsuccessful command disabled.
An accumulator stores a running total; here, total accumulates accepted payload sizes. An iteration is one pass through a loop body.
total=0
accepted=0
for size in 6 0 9 14 4; do
if (( size == 0 )); then
continue
fi
if (( size > 12 )); then
break
fi
(( total += size ))
(( accepted += 1 ))
donea) Find the final accepted size in MB and the number of accepted payloads.
The first payload has size 6 MB. Neither condition succeeds, so both updates run. The running total after this first acceptance is ________, and one payload has been accepted.
The next payload has size zero. Its first condition succeeds, so continue skips both updates and advances to the next listed size. The number of payloads skipped so far is ________.
The 9 MB payload passes both conditions and is added. The resulting total is calculated from the two accepted sizes:
The 14 MB payload triggers break before either update. Execution leaves the loop, so the final 4 MB payload is never examined. It is not merely another skipped pass.
The final accepted size is 15 MB, and the accepted-payload count is 2.
b) The service next runs this conditional. Determine the final value of action.
if (( accepted >= 3 )); then
action=archive
elif (( total > 10 )); then
action=review
else
action=wait
fiUse the values left by the loop: accepted is two and total is fifteen. The first comparison asks whether at least three payloads were accepted. Its truth value is ________, so the archive assignment is skipped.
The second comparison asks whether the accepted size exceeds 10 MB. Since 15 MB exceeds 10 MB, its truth value is ________, and Bash executes the elif branch.
After selecting that branch, Bash skips else; it does not execute every assignment whose position follows the successful condition. The final value of action is review.
A packaging script must increment its counter once for each of three named jobs. Complete the Bash loop by replacing each uppercase placeholder with the required keyword. Keep the existing semicolon and all other code unchanged.
processed=0
for job in manifest payload receipt; OPEN_BODY
(( processed += 1 ))
CLOSE_LOOPReplace OPEN_BODY with and CLOSE_LOOP with .
A Bash test command named probe returns the listed exit statuses on successive calls. Each row represents an independent run with a fresh status sequence. The loop body contains only true and does not change the sequence.
For each row, count calls to probe and executions of the body before the loop terminates. Enter exact integer counts. A sequence may contain statuses that are never reached.
while probe; do
true
doneuntil probe; do
true
done| Loop | Successive probe statuses | Probe calls | Body executions |
| while | 0, 0, 6 | ||
| until | 6, 0, 0 |