This article is part of the Linux Shell Series Tutorial (11), more Linux shell tutorials: Linux Shell Tutorials
In the previous Linux Shell Series tutorial (10) Shell for loop, we have introduced a for loop for Shell loop statements, this article introduces another loop statement in the shell: Shell while loop.
Shell while loop syntax and features
The syntax for the Shell while loop is as follows:
While Commanddo Statement (s) to being executed if command is Truedone
command is a conditional test, and if the return value is 0 (the condition test is true), it enters the loop, executes the command area, or does not enter the loop.
In the area where the command is executed, you should have a command that alters the condition test so that you have an opportunity to end the execution of a while loop after a finite step (unless you want to perform an infinite loop).
While loops are often used to continuously execute a series of commands or to read data from input files;
Commands are usually test conditions.
Shell While loop use example
After understanding the syntax and features of the shell while loop, let's follow a few examples to learn more about the use of the shell while loop.
Example 1:
Counter=0while [$COUNTER-lt 5]do counter= ' expr $COUNTER +1 ' echo $COUNTERdone
Description: Returns True if counter is less than 5. Counter starting from 0, each time the loop is processed, counter plus 1, until count is 5 terminates.
Output:
1
2
3
4
5
Example 2:
#!/bin/bashwhile Read Textdo echo ${text}done
Note: This example uses read to read the data in the standard input, into the variable text, and if the read data is not NULL, it enters the loop. The row data is then displayed in the loop.
As a final input redirect, the contents of the/home/infile are entered as standard for this script.
The output of this script is the contents of the infile file.
Output:
Hello world!
I am linuxdaxue.com!
Example 3:#!/bin/bashdeclare-i i=1declare-i Sum=0while ((i<=10)) do to sum+=i let ++idoneecho $sum
Note: In this example, the variable i and sum of two int types are declared first, then the loop is entered below, and the loop is jumped out after satisfying the condition.
Result: This example is a thought topic left to everyone, you can test it yourself, or follow my public number (No.: Linuxdaxue), send "shell while loop" to see the answer.
Well, the contents of the shell while loop are introduced to you today. For more Linux shell tutorials see: Linux Shell Series Tutorials
This article by Linux technology talent "Daxue" published in: Linux University
This article fixed link: Linux Shell series Tutorial (11) Shell while loopLinux Shell Series Tutorial (11) Shell while loop