Unix / Linux Shell - The for Loop
The for loop operates on lists of items. It repeats a set of commands for every item in a list.
for var in word1 word2 ... wordN do Statement(s) to be executed for every word. done
Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.
Here is a simple example that uses the for loop to span through the given list of numbers −Live Demo
#!/bin/sh for var in 0 1 2 3 4 5 6 7 8 9 do echo $var done
Upon execution, you will receive the following result −
0 1 2 3 4 5 6 7 8 9
Following is the example to display all the files starting with .bash and available in your home. We will execute this script from my root −
#!/bin/sh for FILE in $HOME/.bash* do echo $FILE done
The above script will produce the following result −
/root/.bash_history /root/.bash_logout /root/.bash_profile /root/.bashrc