Loops
Bash has three loop forms — for, while, and until — and which one reads most naturally usually depends on whether you're working through a known list or watching a condition change.
for: looping over a list
bash fruits.sh
#!/bin/bash for fruit in apple banana cherry; do echo "I like $fruit" done
Terminal output
I like apple I like banana I like cherry
for: looping over files
A bare glob like *.txt in a for loop expands to every matching filename — the right way to process a set of files:
bash list-txt.sh
#!/bin/bash for file in *.txt; do echo "Found: $file" done
Terminal output
Found: notes.txt Found: report.txt
Note: loop over
*.txt directly, never over $(ls *.txt). Parsing ls's output breaks on filenames with spaces and adds nothing a glob doesn't already do — it's a well-known anti-pattern in shell scripting.while and until
while keeps looping as long as its condition is true; until is the mirror image — it loops as long as its condition is false:
bash countdown.sh
#!/bin/bash count=5 while [[ $count -gt 0 ]]; do echo "$count..." count=$((count - 1)) done echo "Liftoff!"
Terminal output
5... 4... 3... 2... 1... Liftoff!
break and continue
bash skip-and-stop.sh
#!/bin/bash for n in 1 2 3 4 5 6; do if [[ $n -eq 3 ]]; then continue fi if [[ $n -eq 5 ]]; then break fi echo "n = $n" done
Terminal output
n = 1 n = 2 n = 4
Caution:
while true; do ... done loops forever unless something inside explicitly breaks out or the script is killed. Double-check every open-ended loop has a real exit path before you run it.