bhylu.com

Advertisements

Bash for and while Loops

Iterate over an array and keep a running total in the current shell.

How it works

Loops repeat commands over a sequence or while a condition succeeds. A quoted array expansion preserves each element as one value, unlike a whitespace-separated command substitution. while is useful for stream processing, but a pipeline can place its body in a subshell. Define termination and bounds so an unexpected value cannot create an endless background task.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

Download complete source

Example

loops.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
counts=(8 5 3)
total=0
for count in "${counts[@]}"; do
    ((total+=count))
done
[[ $total -eq 16 ]] || exit 1
step=0
while (( step < 2 )); do
    ((step+=1))
done
printf "Total %d sheets; while iterations %d\n" "$total" "$step"

Expected result

Total 16 sheets; while iterations 2

The first loop adds three known integers and the second stops after two iterations. Increment forms have exit statuses too: an arithmetic expression that evaluates to zero returns failure status, which matters when combined with errexit. Write expected status handling explicitly instead of assuming every arithmetic command is equivalent.

Primary technical reference: Bash documentation.