A For loop is, as its name says a loop that executes certain code or commands for a given number of datum.

From Wikipedia:

for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement.

For Loop Syntax

If you plan to use it in the command line, the best syntax to apply is:

for: for NAME [in WORDS ... ] ; do COMMANDS; done

Example:

This for loop example will print all files in a given directory, in fact it will act almost the same as the ls command.

for i in $( ls ); do echo $i; done

For Loop example explained

For every i which takes the value of ls output, execute echo $i which actually print the name of the file, and then pass to the next i.

You can also use for loop in a bash shell script, in that case a better syntax of the same example could be:

#!/bin/bash
for i in $( ls )
do
     echo $i
done

But just for reading purposes.

More Bash for loop examples

Counting

#!/bin/bash
for ((i=1;i<=25;i+=1)
do
    echo $i
done

Of course the echo $i could be replaced by any other command you may need to execute 25 times.

You can do the same thing this way

#!/bin/bash
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
do
    echo $i
done

Or this other way

#!/bin/bash
for i {1..25}
do
    echo $i
done

Now, what if you want to use for loop to count in steps of 5, let’s see the next example.

#!/bin/bash
for i {0..25..5}
do
    echo $i
done

Here is the output

0
5
10
15
20
25

And, if you want to count backwards?, here is for loop the example:

#!/bin/bash
for i {25..0..-5}
do
    echo $i
done

And the output

25
20
15
10
5
0

You could have also done this way.

#!/bin/bash
for ((i=25;i>=0;i-=5))
do
    echo $i
done

Exit if something happens

If you want to evaluate some variable and once that variable achieve some value, you want to interrupt the for loop before it ends, you can use if..then and break

Let’s see this simple example.

#!/bin/bash
for i in {1..25}
do
    echo $i
    if [ "$i" = "15" ]
    then
         break
    fi
done

You can also jump over a command if something happens, for that use continue.

#!/bin/bash
for i in {1..25}
do
    if [ "$i" = "15" ]
    then
         continue
    fi
    echo $i
done

The last example will never print the number 15, as it will jump to the next step in for, as soon as i equals 15.