Bash For Loops
A for loop runs a block of commands once for each item in a list. The loop variable holds a different item on each round.
Loop over a list of words
The loop runs once for each fruit in the list. The variable fruit holds a new word on each round.
for fruit in apple banana cherry
do
echo "$fruit"
doneLoop over a number range
The range {1..5} gives the numbers one to five. Each number is printed on its own line.
for num in {1..5}
do
echo "Number $num"
doneThe C-style for loop
This loop starts i at zero and adds one after each round. It stops when i is no longer less than three.
for ((i = 0; i < 3; i++))
do
echo "i is $i"
doneExample
for day in Mon Tue Wed Thu Fri
do
echo "Work day: $day"
done
echo "All five days listed"Key points
- A for loop begins with the word for and ends with the word done.
- The word do marks the start of the loop body.
- The loop variable takes the next list item on each round.
- Brace expansion like {1..5} builds a short range of numbers.
- The C-style for loop uses a start value, a test, and an update.
- List items in a for loop are separated by spaces.
In this example, the loop runs once for each day in the list. The variable day holds Mon first, then Tue, and so on. The final echo runs after the loop has finished.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the range {1..4} give a for loop?