For Loop in Bash
In a programming language, a loop is used to repeat the execution of a block of code until the satisfied defined condition. Which is helpful to perform repetitive tasks. Mainly there are 3 types of loops, for, do, and do-while. In this tutorial, we will discuss for
loop in shell scripting.
The shell scripting also provides for loops to perform repetitive tasks. A basic for loop syntax looks like:
Syntax:
for VARIABLE in PARAM1 PARAM2 PARAM3 do //for-loop statements done
The for loop executes for all the defined parameters once. Loop scope is started with a keyword “do” and ended with another keyword “done”. All the statements must be written inside the scope of the loop.
As per the syntax, VARIABLE is initialized with the parameter’s value which can be accessed inside the for loop scope. These parameters can be any number, string, etc.
#1. Bash – For Loop Example
Check below basic for loop which iterates 5 times.
1 2 3 4 5 6 | #!/bin/bash for i in 1 2 3 4 5 do echo "$i" done |
You can also define a range with for loop in the bash script with numeric values.
1 2 3 4 5 6 | #!/bin/bash for i in {1..5} do echo "$i" done |
The arguments can be also a string like:
1 2 3 4 5 6 | #!/bin/bash for day in SUN MON TUE WED THU FRI SUN do echo "$day" done |
#2. Bash – For Loop in C Style
You can also write for loop in bash script similar to for loop in c programming. For example to print 1 to 10 numbers.
1 2 3 4 5 6 | #!/bin/bash for ((i=1; i<=10; i++)) do echo "$i" done |
#3. Bash – For Loop with Files
You can access filenames one by one in for loop under the specified directory. For example, read all files from the current directory.
1 2 3 4 5 6 | #!/bin/bash for fname in * do ls -l $fname done |
The above loop will iterate the number of times as the number of files available. It will select one by file in each iteration.