For Loops
Repeat for each item.
Rename a hundred photos. Check twenty servers. Back up every folder. Whenever you need to do the same thing to many items, a loop does the repeating for you.

- A hundred photos
- Twenty servers
- Let a loop repeat it
sizes.sh
For F in, then a list. Here the list is every JPG in Pictures. For each one, bash puts the file name in F, and runs the lines between do and done. Inside, stat dash C percent S gets the file's size in bytes.
#!/bin/bash
for f in Pictures/*.jpg; do
size=$(stat -c %s "$f")
echo "$f is $size bytes"
doneLooping
The loop runs once for each photo. And loops work right in the terminal too, on one line, with semicolons. Here we loop over three words, and echo each one.
./sizes.sh Pictures/beach.jpg is 24000 bytes Pictures/party.jpg is 31000 bytes for x in red green blue; do echo "Colour: $x"; done Colour: red Colour: green Colour: blue
Things to loop over
You can loop over a list of words, over files matching a wildcard, over all the script's arguments with dollar at, or over a range of numbers, using braces. One, dot dot, five, gives one to five.
| key | value |
|---|---|
| for x in a b c | a list of words |
| for f in *.txt | matching files |
| for a in "$@" | the arguments |
| for i in {1..5} | numbers 1 to 5 |
Summary
For, in, a list, do, and done. The loop runs once for each item. Next, while loops, that keep going as long as something is true.
Key takeaways- for x in list; do … done
- *.jpg
- {1..5}