28_shell language -- while and until loop (while, until, sleep)

Source: Internet
Author: User

In the for loop described earlier, you must first create an element list to determine the number of cycles. However, consider the following example: If you enter "quit", the program will exit, otherwise, convert the characters entered by the user into uppercase letters, such as and to and exit to exit. In this example, you cannot create an element list, because you cannot determine when the user enters the quit, and you cannot determine how many times you want to loop. To solve this problem, we need to introduce a new mechanism: While and. While and until are especially suitable for situations where the number of loops is unknown. Of course, they also apply to situations where the number of loops is known.

I,WhileUsage

The basic format of while is:

WhileTest condition; do

Statement 1

Statement 2

...

Done

It means that when the condition is met, the loop is executed until the condition is not met, and the loop is exited. It is similar to the use of IF, except that if is executed only once, while tests the conditions repeatedly and executes until the conditions are not met. So how can we make the conditions not meet? This requires changing the values of the corresponding variables in the initial test conditions in the loop body. If the values do not change, an endless loop will be formed.

 

Ii. WhileCyclic instance demonstration

Example 1.Use whileCalculate 100 in cyclesSum of all positive integers:

[[Email protected] tutor] # vimsum_while.sh

#!/bin/bashSum=0Count=1while [ $Count -le 100 ]; do       Sum=$[$Sum+$Count]        let Count++doneecho $Sum

 

[[Email protected] tutor] # bashsum_while.sh

5050

 

Example 2.Computing 100The sum of all the even numbers;

[[Email protected] tutor] # vimeven_sum_while.sh

#! /Bin/bashevensum = 0 count = 0 while [$ count-Le 100]; do letevensum + = count let Count + = 2 # Use + = to add a number of doneecho $ evensum

 

[[Email protected] tutor] # basheven_sum_while.sh

2550

 

This program can also be written in the following form:

[[Email protected] tutor] # vimeven_sum_while.sh

#! /Bin/bashevensum = 0 count = 0 while [$ count-Le 100]; do if [$ [$ count % 2]-EQ 0]; then letevensum + = $ count fi let Count ++ doneecho $ evensum # although this method looks more complex than the previous method, it has better scalability, such as the sum of any odd numbers, the sum of 3 multiples and so on


[[Email protected] tutor] # basheven_sum_while.sh

2550

 

If you want to traverse each row of a file, you can use the while loop with the input redirection method to redirect the file to be read after the done. Its usage is as follows:

 

Whileread line; do

Statement1

Statement2

...

Done </path/to/somefile

 

Example 3.If the user IDIf it is an even number, its name and shell are displayed.To all users:

[[Email protected] tutor] # vimread_line.sh

#! /Bin/bashwhile read line; do # Here, read line indicates reading a row of the/etc/passwd file, put the read content into the line variable uid = 'echo $ Line | cut-D:-F3 'If [$ [$ uid % 2]-EQ 0]; then ECHO $ Line | cut-D:-F1, 7 fidone </etc/passwd

[[Email protected] tutor] # bashread_line.sh

root:/bin/bashdaemon:/sbin/nologinlp:/sbin/nologinshutdown:/sbin/shutdownmail:/sbin/nologinuucp:/sbin/nologingames:/sbin/nologinftp:/sbin/nologinrpc:/sbin/nologinavahi-autoipd:/sbin/nologinnfsnobody:/sbin/nologinhaldaemon:/sbin/nologingdm:/sbin/nologinntp:/sbin/nologinapache:/sbin/nologinsaslauth:/sbin/nologinsshd:/sbin/nologintcpdump:/sbin/nologinuser1:/bin/bashuser3:/bin/bashuser5:/bin/bashuser7:/bin/bashuser9:/bin/bashhello:/bin/tcshhadoop:/bin/bash

 

Example 4: Converts the characters entered by the user to uppercase, except for quit.(Meet quitExit ):

[[Email protected] tutor] # vimquit_by_user.sh

#!/bin/bashread -p "A string: " Stringwhile [ "$String" != ‘quit‘ ]; do        echo $String |tr ‘a-z‘ ‘A-Z‘        read -p"Next [quit for exit]: " Stringdone

[[Email protected] tutor] # bashquit_by_user.sh 

A string: sd gfdgSD GFDGNext [quit for exit]: [email protected][email protected]Next [quit for exit]: exitEXITNext [quit for exit]: quit[[email protected] tutor]#

 

Example 5, Use whileCyclic Statistics/etc/rc. d/init. d/functionsMedium #Number of lines starting;

[[Email protected] tutor] # vimnum_lines_while.sh

#! /Bin/bashnum = 0 while read line; do echo $ Line | grep "^ [: Space:] * # "&>/dev/null & let num ++ # Start, in addition, use & to replace ifdone for rows starting with space and # </etc/rc. d/init. d/functionsecho "total $ num lines start #."

 

[[Email protected] tutor] # bashnum_lines_while.sh

Total 70 lines start with #.

 

III,UntilUsage of loops

The until and while loops are similar. They are used when the number of loops is unknown. The format of until is as follows:

 

UntilTest condition; do

 Statement 1

 Statement 2

...

Done

 

In contrast to while, until exits the loop when the condition is met, and runs the statement when the condition is not met. In fact, until and while can be exchanged. When the backend of the while condition is met, it is.

 

IV,UntilCyclic instance demonstration


Example 6.UseRewrite Example 1, Computing 100Sum of all positive integers:

[[Email protected] tutor] # vimsum_until.sh

#! /Bin/bashsum = 0 count = 1 until [$ count-GT 100]; do # Use le in while, the condition for until and while is the opposite: letsum + = $ count let Count ++ doneecho $ sum

[[Email protected] tutor] # bashsum_until.sh

5050

 

Example 7.UseExample 4, Converts the characters entered by the user to uppercase, except for quit(Meet quitExit ):

[[Email protected] tutor] # vimquit_until.sh

#! /Bin/bashread-P "A String:" stringuntil ["$ string" = 'quit']; do # Run the command when $ string is not equal to quit in the while loop, until echo $ string | tr 'a-z'' A-Z' read-P "next [quit for exit]:" stringdone

[[Email protected] tutor] # bashquit_until.sh

A String: sdf opqSDF OPQNext [quit for Exit]: 123#fsd123#FSDNext [quit for Exit]: QuitQUITNext [quit for Exit]: quit

 

Example 8, Every 5View hadoop in secondsWhether the user logs on. If you log on, the user logs on and exits. Otherwise, the current time is displayed, and the hadoopNot logged on:

 

Here we need to introduce a new commandSleepThis command indicates sleep, followed by the number of seconds

 

[[Email protected] tutor] # mansleep

Sleep (1) usercommands sleep (1)

Name

Sleep-delayfor a specified amount of time

Synopsis

Sleep Number [suffix]...

 

If you want to determine the user currently logged on, you can use the who command, and to determine whether the hadoop user has logged on, you can use the grep command:

 

[[Email protected] tutor] # vimhadoop_login.sh

#! /Bin/bashuntil who | grep "^ hadoop" &>/dev/NULL; do # Use the who command to view the currently logged-on user # Because who is a command rather than an expression, therefore, [] Date sleep 5 done echo "welcom back, hadoop! "

To better understand the logic of the above program, you can rewrite it:

 

[[Email protected] tutor] # vimhadoop_login.sh

#! /Bin/bashwho | grep "^ hadoop" &>/dev/nullretval =$? # First run the WHO and grep commands # Then extract the execution status returned value until [$ retval-EQ 0]; do # If the execution status returned value is 0, if the WHO and grep commands are successfully executed, stop executing the cycle body date sleep 5 who | grep "^ hadoop" &>/dev/null retval =$? # If the date and sleep commands are executed, run the WHO and grep commands again to check whether the hadoop user has logged on to done echo "welcomback, hadoop! "

 

[[Email protected] tutor] # bashhadoop_login.sh

Sat Aug 16 09:55:37 EDT 2014sat Aug 16 09:55:42 EDT 2014sat Aug 16 09:55:47 EDT 2014 # enable another terminal and log on to welcom back, hadoop with a hadoop user!


This article from the "sword without a front of a coincidence not work" blog, please be sure to keep this source http://wuyelan.blog.51cto.com/6118147/1543674

28_shell language -- while and until loop (while, until, sleep)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.