Shell programming while & amp; until loop details (Code instance), shellwhile

Source: Internet
Author: User

Shell programming-detailed explanation of the while & until loop (Code instance), shellwhile

Loop statement commands are often used to execute a command or a group of commands, so they are stopped when the conditions are not met. In shell scripts, loop statements are commonly used as while until for select loop statements.

The while LOOP statement is mainly used to repeatedly execute a group of commands or statements. In actual enterprise applications, it is often used for programs that continuously run daemon.

1. In so many statements, the while loop has its syntax format, as follows:

While <conditional expression> do command... done

I still don't understand the above syntax? There is no relation to one sentence: The while LOOP statement will judge the conditional expression followed by the while clause. If the conditional expression is true, run the command or statement in the while LOOP body, every time a while clause is executed to done, the while clause is re-determined to determine whether the while clause is true until the Condition Clause fails.

Have you understood the explanation? It does not matter as follows:

#!/bin/bashwhile ((5>3))do        echo "yes yes yes"done

Analysis: we can see that the above is a group of while loops, so after the while is followed by (5> 3), this is called a conditional expression, that is, if 5> 3 is true, then execute the following echo "yes" and when our syntax is executed to done, it will continue to judge if 5 is greater than 3. Then, according to the while LOOP above, this is called an endless loop !!! Because 5 has always been greater than 3 in this life, then if it is true, yes will always be output.

The input result is as follows:

Well, here we should understand the basic operations of the while loop;

2. Here, let's take a look at the sleep command in linux. sleep 1 indicates one second of rest, and sleep 2 indicates two seconds of rest as follows:

#!/bin/bashwhile ((5>3))do        sleep 2        echo "yes yes yes"done

Analysis: if the condition 5> 3 is true, the output is yes after 2 seconds.

3. append the load value to the log file.

#!/bin/bashwhile [ 1 ]do        sleep 2        date >> /root/logdone

Here, date is the current time, so after while, a [1] indicates that this condition is always true.

4. shell scripts run in the background

Example 1:

Explanation:

[Root @ shell-yankerp ~] # Sh a. sh & # Run a. sh in the background and run [1] 66727 [root @ shell-yankerp ~] # Fg # put the script running in the background to run on the foreground. If there are multiple running in the background, + number sh. sh ^ Z # use ctrl + z to pause the current script task [1] + stopped sh. sh [root @ shell-yankerp ~] # Bg # Use bg to run [1] + sh a. sh & [root @ shell-yankerp ~] in the background # Jobs # Use jobs to view the scripts running in the background [1] + running sh a. sh & [root @ shell-yankerp ~] # Fg 1 # Add the fg serial number to place the script running in the background to the foreground sh. sh ^ Z # Run ctrl + z to stop the script task [1] + stopped sh. sh [root @ shell-yankerp ~] # Jobs # Use jobs to view the script running tasks in the background [1] + stopped sh a. sh [root @ shell-yankerp ~] # Kill % 1 # use kill + % to stop the running task [1] + stopped sh a. sh [root @ shell-yankerp ~] # Jobs # view [1] + terminated sh a. sh [root @ shell-yankerp ~] Again #

Image Description:

4. Use the while loop to print 5-1

#!/bin/basha=5while (($a>0))do        echo $a        ((a--))done

Analysis:

A = 5 is a variable.

While ($ a> 0) is also equivalent to (5> 0). Here, 5 is definitely> 0. The condition is true.

Do

Echo $ a here is 5 4 3 2 1 until the condition is not true exit the loop

(--)) Every Cycle 5 is subtracted from 1, then the entire cycle is 5-1 4-1 3-1 2-1 1 1-1, then to 1-1 = 0, the above conditions are 0> 0 No set up exit Loop

Done

The output is as follows:

[root@shell-yankerp ~]# sh a.sh  [root@shell-yankerp ~]#

It should be understandable. Continue to use double brackets for demonstration.

#!/bin/basha=5while [[ $a>0 ]]do        echo $a        ((a--))done

The output is as follows:

[root@shell-yankerp ~]# sh a.sh   [root@shell-yankerp ~]# 

[] No. [$ a-gt 0] is not demonstrated here ~~~

Ii. until Loop

In fact, the until loop is the opposite of the while loop. That is to say, when the conditional expression is not successful, the following loop is entered:

#!/bin/basha=5until [[ $a < 1 ]]do        echo $a        ((a--))done

If the preceding statement a = 5 $ a is 5, then if the statement 5 <1 is not true, it enters the loop, that is, it is opposite. The output is as follows:

Requirement: Use 1 + 2 + 3 + 4 for calculation from 1 to 100, as shown below:

#!/bin/basha=1b=0while (($a <= 100))do        ((b=b+a))        ((a++))doneecho $b

What does it mean:

#! /Bin/basha = 1 # This is a variable a = 1 so a is 1b = 0 # B is 0 while ($ a <= 100 )) # If $ a <= 100 that is to say 1 <= 100 condition is set to 1 <= 100do (B = B + a) # B = B + a, it means: the variable B is equal to 0 + 1 (a ++ )) # a ++ means that if a is cyclically set to a and a is set to + 1, the condition is always true, that is, the endless loop doneecho $ B #============== ========================================================== ========================================================== ======# calculate B = B + a, which is equivalent to 0 + 1 loop to the following a + +, that is, 1 + 1 = 2 execution to done, then loop again here a is equal 2 is 0 + 1 + 2 + 3 + 4 + 5 + 6 + .....

Image Interpretation

The output result is as follows:

[root@shell-yankerp ~]# sh a.sh 5050[root@shell-yankerp ~]#

I hope the readers can understand it. It's just getting around at the beginning.

What is the use of the while loop? It's not just the addition or subtraction above. The actual practice is as follows:

1. Write a script to charge for a mobile phone bill

This is also an example in the book, but I wrote it as follows:

#! /Bin/bashred_col = "\ e [1; 31 m" reset_col = "\ e [0 m ". /etc/init. d/functions zongjia = 30 duanxin = 15 function caidan () {cat <
 
  
/Dev/null if ["$"-ne 0] then echo "Enter {1 | 2 | 3 | 4}" exit 1 fi} function cxdx () {echo "hello, handsome guy, your remaining balance is: $ zongjia"} function fdx () {while: do if ["$ zongjia"-lt $ duanxin]; then action "your current balance is insufficient. Please recharge your account !!! "/Bin/false return 1 else read-p" Enter the content you want to send: "aaa zongjia = $ (zongjia-duanxin) echo" sent successfully, remaining balance: $ zongjia "return 1 fidone} function czhf () {while: do read-p" Enter the balance you want to recharge: "bbb expr $ bb + 1 &>/dev/null if [" $ "-ne 0]; then action "Enter the value"/bin/false exit 1 else zongjia = $ (zongjia + $ bbb) echo "the recharge is successful, and the current balance remains: $ zongjia "return 1 fidone} function exit () {exit 0} function zong () {while: do caidan & panduan case $ NUM in 1) cxdx; 2) fdx; 3) czhf; 4) exit; esacdone} zong
 

It doesn't matter if you don't understand it. The explanation is as follows:

#! /Bin/bashred_col = "\ e [1; 31 m" # define the red variable for a red reset_col = "\ e [0 m" # this is also true. /etc/init. d/functions # load the functions function library zongjia = 30 # The total price is 30 RMB duanxin = 15 # a text message is 15 RMB function caidan () {# define the menu function cat <
 
  
/Dev/null # determine whether the user inputs a value if ["$"-ne 0] # if the value is not then # then echo "Please input {1 | 2 | 3 | 4} "# output this content exit 1 # final exit script fi} function cxdx () {# define the text message query function echo "hello, handsome guy, your current balance remaining: $ zongjia" # echo output this content} function fdx () {# define the function while for sending text messages: # while loop do if ["$ zongjia"-lt $ duanxin]; then # if the total price is less than the price of a text message action "your current balance is insufficient, please recharge your account !!! "/Bin/false # output this content: return 1 # exit function else # Otherwise read-p" Enter the content you want to send: "aaa # Wait for user content to be assigned to aaa zongjia =$ (zongjia-duanxin) # total price = total price-price of one text message echo" sent successfully, the current remaining balance is: $ zongjia "# final output total price return 1 # exit this function fidone} function czhf () {# define the recharge function while: # while loop do read-p "Enter the balance you want to recharge: "bbb # Wait for the user content to be assigned to bbb expr $ bb + 1 &>/dev/null # Check whether the user input is a value if [" $ "-ne 0]; then # If the value action is not a value, enter the value "/bin/false # Enter exit 1 as the value to exit else # Otherwise, zongjia =$ (zongjia + $ bbb )) # total price = total price + user input price echo "recharge successful, current remaining balance: $ zongjia" # final output total price return 1 # exit function and while LOOP fidone} function exit () {# define exit function exit 0 # exit} function zong () {# define the total function while: # while loop do caidan & panduan # Call the menu function and judge the function case $ NUM in # If you enter the following in the $ NUM variable: 1) cxdx; 2) fdx; 3) czhf; 4) exit; esacdone} zong # finally calls the total Function
 

Not eye-catching enough? It does not matter, as shown in the following figure:

The running result is as follows:

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.