for loop

Loops are used to perform actions over and over again until a condition is met (or until a condition is no longer met). They are used to repeat a block of code for a known or unknown number of times, depending on the type of loop. Three types of loops are often used: for, while, and until.

The for loop repeats the commands between the do and done statements a specified number of times. Each time the script carries out the commands in the loop, a variable is given a a new value. Here is the syntax of the for loop:

{ commands }

VAR_NAME is any Bash variable name. LIST can be any list of values or anything that generates a list. Commands inside the brackets are executed once for each item in the list. That means that if the list of values contains 4 items, the for loop will be executed 4 times. Each element in the LIST is separated from the next by whitespace. The current item from the list will be stored in the variable VAR_NAME each time through the loop.

Here is an example:

for NUM in 2 12 17 104 10003
echo “The number is $NUM.”

In the example above you can see that the loop has been executed 5 times. Each time the different number has been stored in the variable VAR_NAME and displayed on the screen:

linux for loop

Subscribe to our Newsletter

Like us on Facebook

Geek University 2019