Home > Operation and Maintenance > Linux Operation and Maintenance > Using for loop in bash shell script

Using for loop in bash shell script

不言
Release: 2019-03-22 15:17:16
Original
4324 people have browsed it

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.

Using for loop in bash shell script

Syntax:

for VARIABLE in PARAM1 PARAM2 PARAM3
do
// commands to execute
done
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

We can also pass all filenames as parameters to the loop.

foriin*do
   echo "This file is $i"
done
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template