Loops are very useful for executing repeated statements in any programming language. for loops can also be used in bash scripts. In this article, we will introduce the usage and examples of for loop.
Syntax:
for VARIABLE in PARAM1 PARAM2 PARAM3 do // commands to execute done
In the above syntax PARAM1, PARAM2 and PARAM3 are passed as parameters. These parameters can be numbers, strings, or file names. The For loop will be executed 3 times as per the number of parameters passed in the above syntax. VARIABLE is a variable that is initialized one by one using parameter values.
Example of for loop in bash script
To define the number of times to loop, we just pass the number as argument of the variable.
foriin1 2 3 4 5 6do echo "$i" done
We can also define ranges instead of writing each number on recent versions of bash. To define a range we use curly brackets like {STARTNUMBER..ENDNUMBER}.
foriin {1..6} do echo "$i" done
We can also pass a string value as a parameter that defines the number of iterations, passed as a parameter.
for i in SUN MON TUE WED THU FRI SAT do echo "This is $i" done
We can also pass all filenames as parameters to the loop.
foriin*do echo "This file is $i" done
Creating C-like for loops in bash scripts
We can also create C-like code for loops in shell scripts.
Syntax:
or ((EXPR1; EXPR2; EXPR3)) do // commands to execute done
EXPR1 is used for initialization, EXPR2 is used for conditions, and EXPR3 is used for increment/decrement of variable values.
For example, to execute the loop 10 times, we can simply write a for loop
for ((i=1; i<=10; i++)) do echo "$i" done
This article is all over here. For more other exciting content, you can pay attention to the PHP Chinese website Linux tutorial video column!
The above is the detailed content of Using for loop in bash shell script. For more information, please follow other related articles on the PHP Chinese website!