Skip to the workspace
Pebellslearn by building
Loops and Functions  ›  Lesson

while and until Loops

while 14 minA while loop repeats while its test command succeeds and an until loop repeats while it fails, and while read is the standard way to process a file line by line.

shell bash / while and until Loops

Explore each scene at your own pace.

01 · The rule

The rule

while and until Loops

A while loop repeats while its test command succeeds and an until loop repeats while it fails, and while read is the standard way to process a file line by line.

Process input line by line and define what makes the loop stop.

The folder list for backup.sh is growing, and you would rather keep it in a file, folders.txt, than inside the script. You do not know how many lines it has. A for loop walks a list you already have; a while loop keeps going as long as something is true, such as "there is another line to read".

The rule

while repeats as long as its test succeeds; until, as long as it fails.

Like if, the test is a command, and "succeeds" means exit status 0:

n=3
while (( n > 0 )); do
    echo "$n"
    (( n-- ))
done                      # prints 3, 2, 1

until ping -c 1 backup-server >/dev/null; do
    sleep 5               # keep trying until the server answers
done

The most important while in Bash reads a file line by line:

count=0
while IFS= read -r line; do
    tar -czf "$dest/$count.tar.gz" "$line" && (( count++ ))
done < folders.txt
echo "Archived $count folders"
  • read succeeds while there is a line and fails at the end of the file, which ends the loop.
  • IFS= stops read trimming spaces at the ends; -r keeps backslashes.
  • < folders.txt after done feeds the file to the whole loop.

while true; do ... done loops forever, until something inside uses break or exit.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.