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.


status=0⇒condition succeedsstatus≠0⇒condition does not succeed\begin{aligned} \text{status} = 0 &\quad\Rightarrow\quad \text{condition succeeds} \\ \text{status} \ne 0 &\quad\Rightarrow\quad \text{condition does not succeed} \end{aligned}


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.


Shell
if false; then
  printf 'primary route\n'
elif true; then
  printf 'backup route\n'
else
  printf 'no route\n'
fi


Here, 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.


Shell
case stop in
  start) printf 'starting\n' ;;
  stop)  printf 'stopping\n' ;;
  *)     printf 'unknown action\n' ;;
esac


This 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.


A while loop tests a command before entering its body and returns to the test after each 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.


Shell
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 ))
done


a) 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:


total=6 MB+9 MB=15 MB\text{total}=6\ \text{MB}+9\ \text{MB}=15\ \text{MB}


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.


Shell
if (( accepted >= 3 )); then
  action=archive
elif (( total > 10 )); then
  action=review
else
  action=wait
fi


Use 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 Bash script sorts a work queue into priority bands by its length. The variable n holds the queue length, and the script then runs the conditional below. Which single word does this snippet print?


Shell
n=4
if (( n > 5 )); then
  printf 'high\n'
elif (( n > 2 )); then
  printf 'mid\n'
elif (( n > 0 )); then
  printf 'low\n'
else
  printf 'zero\n'
fi
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.


Shell
processed=0
for job in manifest payload receipt; OPEN_BODY
    (( processed += 1 ))
CLOSE_LOOP


Replace OPEN_BODY with and CLOSE_LOOP with .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.


Shell
while probe; do
  true
done


Shell
until probe; do
  true
done
LoopSuccessive probe statusesProbe callsBody executions
while0, 0, 6
until6, 0, 0

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice