How do I write a 'for' loop in Bash? How do I write a 'for' loop in Bash? bash bash

How do I write a 'for' loop in Bash?


From this site:

for i in $(seq 1 10);do    echo $idone


for ((i = 0 ; i < max ; i++ )); do echo "$i"; done


The Bash for consists on a variable (the iterator) and a list of words where the iterator will, well, iterate.

So, if you have a limited list of words, just put them in the following syntax:

for w in word1 word2 word3do  doSomething($w)done

Probably you want to iterate along some numbers, so you can use the seq command to generate a list of numbers for you: (from 1 to 100 for example)

seq 1 100

and use it in the for loop:

for n in $(seq 1 100)do  doSomething($n)done

Note the $(...) syntax. It's a Bash behaviour, and it allows you to pass the output from one command (in our case from seq) to another (the for).

This is really useful when you have to iterate over all directories in some path, for example:

for d in $(find $somepath -type d)do  doSomething($d)done

The possibilities are infinite to generate the lists.