This article is the eleventh part of the Linux Shell Scripting Series . For more Linux Shell tutorials, please see: Linux Shell Scripting Series Tutorials
In the last Linux Shell series of tutorials (10) Shell for loop , we have introduced the for loop of the Shell loop statement. This article will introduce another kind of loop statement in Shell: Shell while loop.
Shell while loop syntax and characteristics
The syntax of a shell while loop is as follows:
while command do Statement(s) to be executed if command is true done
command is a conditional test. If the returned value is 0 (the conditional test is true), it will enter the loop and execute the command area, otherwise it will not enter the loop.
In the area where the command is executed, there should be a command that changes the conditional test, so that there is a chance to end the execution of the while loop after a finite number of steps (unless you want to execute an infinite loop).
The while loop is usually used to continuously execute a series of commands, and can also be used to read data from an input file;
Commands are usually test conditions.
Shell while loop usage example
After understanding the syntax and characteristics of the Shell while loop, let's learn more about the use of the Shell while loop through a few examples.
Example 1:
COUNTER=0 while [ $COUNTER -lt 5 ] do COUNTER='expr $COUNTER+1' echo $COUNTER done
Description: Returns true if COUNTER is less than 5. COUNTER starts from 0. Each time the loop is processed, COUNTER increases by 1 until COUNT is 5 and terminates.
output:
1
2
3
4
5
Example 2:
#!/bin/bash while read text do echo ${text} done < /home/infile
Description: This example uses read to read data from the standard input and put it into the variable text. If the read data is not empty, it will enter the loop. Then display the row of data in the loop.
The last thing is input redirection, and the content of /home/infile is used as the standard input of this script.
The output of this script is the content of the infile file.
output:
Hello world!
I am linuxdaxue.com!
Example 3:
#!/bin/bash declare -i i=1 declare -i sum=0 while ((i<=10)) do let sum+=i let ++i done echo $sum
Explanation: In this example, two variables i and sum of type int are firstly declared, and then the following loop is entered, and the loop is jumped out after the conditions are met.
Result: This example is a question for everyone to think about. You can test it yourself, or follow my WeChat public account (WeChat: Linuxdaxue) and send [shell while loop] to check the answer.
Well, the contents of the Shell while loop will be introduced to you today. For more Linux Shell tutorials, please see: Linux Shell Scripting Series Tutorials
Original: Linux Shell series of tutorials (11) Shell while loop
This article is transferred from: Linux Shell Scripting Tutorial Series (11) Shell while loop