For loop in Shell

The for loop works on lists of items (items). It repeats a set of commands for each item in a list.

The for loop works on lists of items (items). It repeats a set of commands for each item in a list.

Syntax in Unix / Linux

 for var in word1 word2 . wordN do cac lenh de thuc thi cho moi word . done 

Here, var is the name of a variable and word1 to wordN is a sequence of characters separated by spaces. Each time the loop executes, the value of the var variable is set to the next word in the list of words, from word1 to wordN.

For example in Unix / Linux

Here is a simple example that uses a for loop to browse the list of numbers.

 #!/bin/sh for var in 0 1 2 3 4 5 6 7 8 9 do echo $var done 

It will produce the following result:

 0 1 2 3 4 5 6 7 8 9 

Here is an example to display all files starting with .bash and available in your home directory. I made this script from my root .

 #!/bin/sh for FILE in $HOME /. bash * do echo $FILE done 

It will produce the following result:

 /root/ . bash_history / root /. bash_logout / root /. bash_profile / root /. bashrc 

According to Tutorialspoint

Last lesson: while loop in Shell

Next article: Loop until in Shell

5 ★ | 1 Vote