Control Flow and Script Interfaces

Choose a branch, repeat bounded work, and validate the interface before acting.

if asks whether a command succeeded

if [ -f input.txt ] && [ -r input.txt ]; then
  printf 'input suitable\n'
else
  printf 'input unsuitable\n'
fi

Use the lesson's owned fixture. Status zero selects the first branch. A successful preflight does not guarantee the later read succeeds.

The first matching range wins

records=90
if (( records >= 90 )); then label=high
elif (( records >= 50 )); then label=moderate
else label=low
fi
printf '%s\n' "$label"

Expected: high. Test 49, 50, 89, and 90. Reversing the first two conditions changes which branch can run.

case matches one value against patterns

file='east host.log'
case "$file" in
  *.log) printf 'log name\n' ;;
  *.txt|*.csv) printf 'text data name\n' ;;
  *) printf 'unrecognized suffix\n' ;;
esac

Expected: log name. A filename suffix does not validate its content. End each branch with ;; before the next pattern.

Preserve each item in a list

reports=('east host.txt' '*.txt')
for report in "${reports[@]}"; do
  printf '<%s>\n' "$report"
done

Expected: <east host.txt>, then <*.txt>.

Do not use for line in $(cat file) to read records: splitting loses record boundaries and empty records.

Every loop needs a stopping condition

Form Continue while
for item in values Items remain
for ((i=0; i<3; i++)) Counter condition is nonzero
while command Command succeeds
until command Command fails

A retry maximum matters when success never arrives. Update a while-loop counter before a path that can continue.

Keep record state in the current shell

count=0
while IFS= read -r line || [ -n "$line" ]; do
  count=$((count + 1))
  printf '<%s>\n' "$line"
done < records.txt
printf 'records=%s\n' "$count"

Use the lesson's fixture: a spaced record, a blank record, and a final record without a newline. Expected count: 3.

break and continue change different paths

Command Effect
break Exit the current loop
continue Skip the rest of the current iteration
break 2 Exit two enclosing loops
continue 2 Begin the next iteration of the second enclosing loop

Trace row and column indices in the nested example. A skipped record and a completed search are different report facts.

Read one record before building a record loop

IFS= read -r line assigns a line without trimming whitespace or interpreting backslashes.

  • A newline-terminated empty line is still a successful read.
  • End-of-input returns nonzero, even when a final unterminated value was assigned.
  • || [ -n "$line" ] lets that last nonempty value reach the loop body.
  • < file supplies input to the loop in the current shell.

A pipeline can change where assignment occurs

printf 'hello world\n' | read -r first second

Under normal Bash pipeline behavior, read runs in a subshell. The parent does not retain its assignments. Bash lastpipe settings can alter the last component's environment.

read -r first second < fields.txt

With the supplied file, the current shell retains hello and world. The lesson tests both paths explicitly.

Arguments are separate values

bash show.sh 'east host' '*.log' ''

The lesson's script sees three arguments. "$@" preserves each one, including the empty argument. $# reports the count; $0 reflects the invocation.

A count check does not validate the value. An empty label may need a separate policy.

getopts gives repeatable short options

The lesson uses getopts ':ho:v' option.

  • -h: help, status 0.
  • -o value: report path; a missing value is status 2.
  • -v: diagnostics on standard error.
  • --: stop parsing options before a positional target.

OPTIND is the one-based next-argument index. shift n removes the first n arguments. After parsing, shift "$((OPTIND - 1))" leaves positional arguments. The supplied script prints configuration; it does not collect a host report.

Verify the interface before collection

Case Expected status
Help / valid configuration 0
Missing option value / unknown option / wrong count 2
Target is not a directory 1

Capture stdout, stderr, and status separately. Confirm that selecting a report path does not create it. The graded lab applies this on your VM.

Linuxize loop and Bash sources are linked in the lessons; fixtures and explanations are original adaptations.