Course outline · 0% complete

0/29 lessons0%

Course overview →

while loops and reading lines

lesson 9-2 · ~9 min · 25/29

Repeat while a condition holds

for walks a known list. while repeats as long as a condition command succeeds, using the same [ ] tests from lesson 8-3:

count=1
while [ "$count" -le 3 ]; do
  echo "lap $count"
  count=$((count + 1))
done

New piece: $(( )) is arithmetic expansion, the shell's calculator. $((count + 1)) evaluates to the sum. Forget the increment line and the condition never becomes false: an infinite loop. (Ctrl+C from lesson 6-2 is the escape hatch.)

Code exercise · bash

Run it: a counter climbing from 1 to 3.

The classic: process a file line by line

read -r (from lesson 8-3) grabs one line of stdin. Put it as a while condition and redirect a file into the loop with < (lesson 5-1), and you get the standard line-by-line pattern:

while read -r name; do
  echo "Welcome, $name"
done < guests.txt

read succeeds (exit 0) for every line and fails at end of file, which ends the loop. Every log processor, CSV importer, and batch job in shell history is built on this shape.

Code exercise · bash

Run it. Three guests go into a file, and the while-read loop greets each line.

Quiz

What ends a `while read -r line; do ...; done < file` loop?

Code exercise · bash

Your turn. Sum the numbers 1 through 5 with a for loop and arithmetic expansion, keeping a running `total`. Expected output: ``` sum: 15 ```