While loops and until: the number of cycles is variable.
One, while loop
1. Format:
While condition test; do
Circulation body;
Done
Example: The and of all positive integers in 1-100 with while.
#!/bin/bash
Declare-i Sum=0,i=1
While [$i-le];d o
Let sum+= $i
Let i++
Done
Echo $sum
Example: Use while to find all even numbers within 1-100 and.
#!/bin/bash
Declare-i sum=0,i=2
While [$i-le];d o
Let sum+= $i
Let i+=2
Done
Echo $sum
Example: The keyboard prompts the user to enter characters, converts the user input lowercase letters to uppercase,
Once the conversion is done, remind the user to enter again and convert again until quit is entered.
Quit says quit.
#!/bin/bash
Read-p "Enter a word:" Word
while [["$word"! = "Quit"]];d o
echo $word |tr ' A-Z ' A-Z
Read-p "Enter A word again:" Word
Done
Example: Prompt the user to enter a user name, if present, displays the user UID and shell information, otherwise, the user is not displayed;
When the display is complete, prompts the user to enter again, or quit if quit.
#!/bin/bash
Read-p "Enter a username:" username
while [["$userName"! = "Quit"]];d o
If ID $userName &>/dev/null;then
grep "^ $userName \>"/etc/passwd |cut-d:-f3,7
Else
echo "$userName is not exist."
Fi
Read-p "Enter a username again:" username
Done
Example: Prompt the user to enter a user name,
If it does not exist, prompt the user to enter it again.
If present, determine if the user is logged in,
If you are not logged in, you are prompted to "$userName is isn't here.",
Then stop for 5 seconds and again determine if the user is logged in,
Until the user logs on to the system, "$userName is on" appears.
#!/bin/bash
Read-p "Enter A user name:" UserName
While! ID $userName &>/dev/null;do
Read-p "Enter a user name again:" UserName
Done
While! W.H.O. | grep "^ $userName" &>/dev/null;d o
echo "$userName is isn't here."
Sleep 5
Done
echo "$userName is on."
Second, until cycle: The condition is not satisfied, then the loop, otherwise exit (visible in the while opposite).
Example: With Untile cycle, the sum of all positive integers within 100 is obtained.
#!/bin/bash
Declare-i sum=0
Declare-i I=1
Untile [$i-gt];d o
Let sum+= $i
Let i++
Done
Echo $sum
Three, the combination condition test:
1. Logic and:
[Condition1] && [Condition2]
[Condition1-a Condition2]
[[Condition1 && Condition2]]
Note that:&& can only be used in double brackets [[]].
2. Logic or:
[Condition1] | | [Condition2]
[Condition1-o Condition2]
[[Condition1 | | condition2]]
Note: | | Can only be used in double brackets [[]].
3. Use the while loop to read the file one line at a time until the end of the file;
While read line;d o
Loop body
Done </path/to/somefile
Example: Removing a user with a default shell of bash on the current system
#!/bin/bash
While Read Line;do
[[' Echo $line |cut-d:-f7 ' = = '/bin/bash ']] && echo $line |cut-d:-F1
Done </ETC/PASSWD
While and until loops