for loop

The simplest for loop iterates over a list of strings, as shown below:

for variable in list of words
do
commands
done

Here is a sample that creates five folders.

[alice@localhost sandbox]$ ls
[alice@localhost sandbox]$ for f in 1 2 3 4 5
> do
> mkdir folder$f
> done
[alice@localhost sandbox]$ ls
folder1  folder2  folder3  folder4  folder5

We can also write the for loop in one line by using semicolon separators.

for variable in list of words; do commands; done

Note that we can use wild card expressions in the for loop list as shown in the example below:

[alice@localhost sandbox]$ for f in folder*; do ls -ld $f; done
drwxrwxr-x 2 alice alice 4096 Dec  5 14:17 folder1
drwxrwxr-x 2 alice alice 4096 Dec  5 14:17 folder2
drwxrwxr-x 2 alice alice 4096 Dec  5 14:17 folder3
drwxrwxr-x 2 alice alice 4096 Dec  5 14:17 folder4
drwxrwxr-x 2 alice alice 4096 Dec  5 14:17 folder5

We can also execute a program inline and take its output as the list of strings that a for loop iterates over. See the example below. In this example, the first command creates an empty file in the /tmp directory. Then the for loop uses the find command to list the full path to any file with the .txt extension in the user's home directory. The cat command with » concatenates all such files into the one file in /tmp directory!

[alice@localhost sandbox]$ echo > /tmp/all-my-text-in-one-file.txt
[alice@localhost sandbox]$ for name in $(find ~ -name "*.txt" -print)
> do
>   cat $name >> /tmp/all-my-text-in-one-file.txt
> done

We can also write for loops that look more like in Java using the following syntax:

for ((expr1; expr2; expr3)) do commands; done

See below for an example:

[alice@localhost sandbox]$ for ((i=0; i<10; i++))
> do
>   echo $i
> done
0
1
2
3
4
5
6
7
8
9

We can also use printf with bash. It uses formatting similar to printf in Java (and C).

[alice@localhost sandbox]$ for ((i=0; i<20; i++)); do printf "%02d\n" $i; done
00
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19

Try the above loop using echo $i instead of the printf and notice the difference.

We can also nest for loops. For example:

[alice@localhost sandbox]$ for i in 1 2 3
> do
>   for j in 1 2
>   do
>     echo $i "*" $j "=" $[i*j] 
>   done
> done
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
3 * 1 = 3
3 * 2 = 6
[alice@localhost sandbox]$