Shell While Loops
A while loop is a way to repeat commands while a command succeeds. It checks its command before each run, and stops as soon as that command fails.
Read a file line by line
Read takes one line each time round the loop.
while read -r line; do
echo "Line: $line"
done < notes.txtRead a shopping list
Each item gets its own run of the block.
while read -r item; do
echo "Buy $item"
done < shopping.txtRead the data file
The header row is read just like the rest.
while read -r line; do
echo "Row: $line"
done < data.csvWait with until
Until stops as soon as its command succeeds.
until [ -f done.txt ]; do
echo "Waiting"
touch done.txt
doneExample
while read -r line; do
echo "Task: $line"
done < notes.txt
until [ -f finished.txt ]; do
echo "All tasks listed"
touch finished.txt
doneKey points
- While loop: while runs the block again and again while its command succeeds.
- Until loop: until runs the block while its command fails, and stops when it succeeds.
- Read loop: while read -r line reads a file line by line.
- Use read -r to keep each line exactly as it is written.
In this example, the while loop reads notes.txt line by line and prints each task. Then the until loop runs once, prints All tasks listed, and makes finished.txt so it stops.
Note
A while loop that never fails runs forever, so the loop must change something each time.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When does a while loop stop?