A concise tutorial on shell script while, until Loop _linux shell

Source: Internet
Author: User


One, while loop



The while loop is used to continuously execute a series of commands and to read data from an input file; a command is usually a test condition. The format is:


 code as follows:

While command
Todo
Command1
Command2
...
CommandN
Done





command completes, control returns to the top of the loop, starting from scratch until the test condition is false.



The following is a basic while loop, where the test condition is: If counter is less than 5, then the condition returns True. Counter starting from 0, counter plus 1 each time the loop is processed. Run the above script, return the number 1 to 5, and then terminate.





 code as follows:

Counter=0
While [$COUNTER-lt 5]
Todo
counter= ' Expr $COUNTER +1 '
Echo $COUNTER
Done





Run script, Output:
1
2
3
4
5



The while loop can be used to read keyboard information. In the following example, the input information is set to the variable film, and the <Ctrl-D> ends the loop.

 code as follows:


echo ' type <CTRL-D> to terminate '
Echo-n ' Enter your most liked film: '
While Read FILM
Todo
echo "yeah! Great film The $FILM "
Done





Run the script with the output similar to the following:
Type <CTRL-D> to terminate
Enter your most liked film:sound of Music
yeah! Great film The Sound of Music



Second, until cycle



The Until loop executes a series of commands until the condition is true. The Until loop and the while loop are just the opposite of how they are handled. The general while loop is better than the until loop, but at some point-and only in rare cases, the until loop is more useful.



The Until loop format is:


 code as follows:
Until conditions
Command1
Command2
...
CommandN
Done

The condition can be any test condition, the test occurs at the end of the loop, so the loop executes at least once-please note this.




Related Article

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.