For Loop in Bash
In a programming language, a loop is used to repeat the execution of a block of code until the defined condition. Which helps 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 this:
Syntax:
The for loop executes for all the defined parameters once. Loop scope is started with a keyword “do” and ends 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.
You can also define a range with a for loop in the bash script with numeric values.
The arguments can be also a string like:
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.
3. Bash – For Loop with Files
You can access filenames one by one in the for loop under the specified directory. For example, read all files from the current directory.
The above loop will iterate the number of times as the number of files available. It will select one file in each iteration.
0 Comments
CAN FEEDBACK
Emoji