AI Hints
Home›Linux Tutorial›Decisions and Loops
Linux · Lesson 105 of 120

For Loops

Repeat for each item.

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

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.

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

nano sizes.shbash
#!/bin/bash
for f in Pictures/*.jpg; do
  size=$(stat -c %s "$f")
  echo "$f is $size bytes"
done

Looping

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.

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

keyvalue
for x in a b ca list of words
for f in *.txtmatching 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}
Next up: While Loops — repeat while true