For Loops (Shell Scripting)

A for loop in a shell script takes on a different appearance than for loops in many other languages, but ends in the same result.

When declaring the for loop, an index value is provided, and the index successively takes on each value in the list until the end of the list. This is demonstrated by:

#!/bin/bash

for index in 1 2 3 4 5
do
    echo $index
done

This output of the preceding code would simply be:

1
2
3
4
5

By combining a for loop with the 'seq' command, you can avoid the effort of typing every entry in the list:

#!/bin/bash

for i in $(seq 1 100)
do
    echo $i
done

You can also execute commands within the list of a for loop to get some useful results. The following snippet prints the name of each file in the users home directory:

#!/bin/bash

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

or using an alternate syntax:

#!/bin/bash

for i in `ls $HOME`
do
    echo $i
done
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License