While Loops
Repeat while true.
A for loop works through a list. A while loop is different. It keeps going, as long as a test stays true. It's perfect for countdowns, retries, and reading a file line by line.

- for: work through a list
- while: keep going while true
- Countdowns, retries, files
countdown.sh
Count starts at three. While count is greater than zero, echo it, and take one away. Dollar, double brackets, does arithmetic. When count reaches zero, the test fails, the loop ends, and we lift off.
#!/bin/bash
count=3
while [ "$count" -gt 0 ]; do
echo "$count..."
count=$((count - 1))
done
echo "Lift off!"Counting and reading
Here's the countdown. And here's the most common while loop of all. While read line, with the file fed in at the bottom using a less than sign. Running it reads notes dot TXT one line at a time, and numbers each line.
./countdown.sh 3... 2... 1... Lift off! cat lines.sh #!/bin/bash n=1 while read -r line; do echo "Line $n: $line" n=$((n + 1)) done < notes.txt ./lines.sh Line 1: Buy milk Line 2: Call Mum Line 3: Learn Linux
Careful with forever
If the test never becomes false, the loop never ends. Sometimes that's what you want, like a service that checks something every minute, with while true, and sleep sixty. If it's a mistake, control C stops it.
| key | value |
|---|---|
| while [ test ] | repeat while true |
| $((n + 1)) | arithmetic |
| while read -r line | each line of a file |
| while true | forever, until Ctrl+C |
Summary
While repeats as long as a test is true. Dollar double brackets does sums, and while read handles files line by line. Next, functions, reusable blocks of code.
Key takeaways- while [ test ]; do … done
- $(( ))
- while read -r line