当前位置:网站首页>Shell script -while loop explanation

Shell script -while loop explanation

2022-07-01 08:48:00 Little snail's way

while Cycle is Shell The simplest kind of loop in a script , When the conditions are met ,while Execute a set of statements repeatedly , When conditions are not met , Quit while loop .

Usage is as follows :

while condition
do
    statements
done

condition Express judgment condition ,statements Indicates the statement to be executed ( There can be only one , There can be more than one ),do and done All are Shell Keywords in .

Code 1: Calculate from 1 Add to 100 And .

#!/bin/bash
i=1
sum=0
while ((i <= 100))
do
    ((sum += i))
    ((i++))
done
echo "The sum is: $sum"

Output :

The sum is: 5050

stay while In circulation , As long as the judgment conditions are true , The loop will execute . For this code , As long as the variable i Is less than or equal to 100, The cycle will continue . Each loop gives a variable sum Add variables i Value , Then give the variable i Add 1, Until variable i The value is greater than 100, The cycle stops .

i++ Statement makes i Gradually increase the value of , Make the judgment conditions more and more close to “ Don't set up ”, Finally exit the loop .

Code 2: Calculate from m Add to n Value .

#!/bin/bash
read m
read n
sum=0
while ((m <= n))
do
    ((sum += m))
    ((m++))
done
echo "The sum is: $sum"

Output :

1
100
The sum is: 5050

Code 3: Implement a simple addition calculator , The user enters a number per line , Calculate the sum of all numbers .

#!/bin/bash
sum=0
echo " Please enter the number you want to calculate , Press  Ctrl+D  Key combination ends reading "
while read n
do
    ((sum += n))
done
echo "The sum is: $sum"

Output :

 Please enter the number you want to calculate , Press  Ctrl+D  Key combination ends reading 
333
444
111
The sum is: 888

Ctrl+D Composite key : Read data in the terminal , It can be equivalent to reading data in a file , Press down Ctrl+D The key combination indicates reading to the end of the file stream , here read Will fail to read , Get a non 0 The exit state of the value , Thus, the judgment conditions are not tenable , End of cycle .

原网站

版权声明
本文为[Little snail's way]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010835460247.html