AI Hints
Home›Linux Tutorial›Loops and Functions
Linux · Lesson 106 of 120

While Loops

Repeat while true.

⏱ 2 min read▶ Video at 2:21:57🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

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.

While Loops
From the video: While Loops
  • 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.

nano countdown.shbash
#!/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.

Terminal
./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.

keyvalue
while [ test ]repeat while true
$((n + 1))arithmetic
while read -r lineeach line of a file
while trueforever, 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
Next up: Functions — name a block of commands