Line At A Time
Lesson 6: Looping Over a List
Looping Over a List Repeat the same work once for every item.
1#!/bin/bash
2for pet in cat dog rabbit
3do
4 echo "I have a $pet"
5done
Terminal
$ ./pets.sh
I have a cat
I have a dog
I have a rabbit
Every line, explained
#!/bin/bash
This first line is called the shebang (from "hash bang", the # and ! it starts with). It is not a comment: it tells the computer which program should read the rest of the file. #!/bin/bash means "run this with bash". Every bash script starts with this exact line.
for pet in cat dog rabbit
A for loop takes a list and runs the same lines once for each item in it. Each time round, the loop variable holds the current item. Here the list is written out by hand: three words, separated by spaces. Each time round the loop, the variable pet holds the next one.
do
The body of the loop goes between do and done. Everything in between runs once per item.
echo "I have a $pet"
One line, printed three times, saying something different each time, because $pet changes on every trip around the loop.
done
The body of the loop goes between do and done. Everything in between runs once per item. done closes the loop, the way fi closes an if.