← Lessons/Loops & Conditionals
← Loops & Conditionals

Loop over a range

Learn

The for loop: once per item

A for loop walks through a list, binding each item to a variable in turn and running the body once per item. Picture a checkout conveyor belt: items come past one at a time, and you do the same thing to each.

for host in web1 web2; do
  echo "checking $host"
done

host takes the value web1 and the body runs; then web2 and it runs again. do and done fence the body: everything between them repeats. The list can be anything separated by spaces: numbers, filenames, hostnames, the words in a variable.

Write a for loop that prints the numbers 1, 2, and 3 — each on its own line.

$ bash solution.sh
Loading...

Output

Run your solution to see its output here.