Shell talk about the three for, while, until loop

Source: Internet
Author: User
First, Introduction

In shell programming, circular commands are used to control the execution of certain statements under certain conditions, with three commonly used loop statements: for, while, and until. While loops and for loops belong to the "loop of the type", while the until belongs to the "until loop". Loop control: Break and continue control flow steering.
Second, detailed 1. For loop

(1) The For loop has three structures: one is the list for loop, the second is a for loop without a list. The third type is the C-style for loop.

(2) List for loop

#!/bin/bash

for varible1 in {1..5}
#for varible1 in 1 2 3 4 5
do
     echo "Hello, Welcome $varible 1 times" 
  done

The command between do and done is called the loop body, and the number of executions is the same as the number of constants or strings in the list. For loop, first assigns the first constant or string of the in after list to the loop variable, then executes the loop body, which executes the list, and finally executes the command sequence after the done command. The Sheel support list for loop uses a slightly written count, and the range of the scope is denoted by {1..5} (curly braces cannot be removed or treated as a string). Sheel also supports the implementation of a list for loop in a specified number of steps, such as calculating the sum of all the odd numbers within a 1~100.

#!/bin/bash
sum=0 for

i in {1..100..2} does let
    "sum+=i"
done
    
echo "sum= $sum"
Increments by step 2 of I, calculates the sum value of 2500. You can also use the SEQ command to increment the sum of all the odd numbers within a 1~100 by 2 increments, for I in $ (SEQ 1 2), the SEQ for the starting number of 1, the number of steps to jump 2, and the end condition value to 100.

The For Loop operates on strings, such as displaying all files in the current directory through A For loop.

#!/bin/bash for

file in $ (LS)
#for the file in * does
   echo "file: $file"
done


You can also create a filename extension that matches all the files in the current directory by using the for file in *, the wildcard character *. For pass-through list parameters in a script through the command line

#!/bin/bash

echo "Number of arguments is $#"

echo "What are input is:" for

argument in "$@"
do
    echo " $argument "Done

$ #表示参数的个数, $@ represents a list of arguments and $* displays all the arguments as a string.

(3) without list for loop

The number of parameters and parameters that are set by the user is the same as the For loop list parameters described above.

#!/bin/bash

echo "Number of arguments is $#"

echoes "What are you input are:" for

argument do
    echo "$argumen T "done
The $@ parameter list is less than the above code, and the $* parameter string.

(4) Class C-style for loop

Also known as the Count cycle

#!/bin/bash for

((integer = 1; integer <= 5; integer++))
does
    echo "$integer"
done

The first expression in for (integer = 1) is the statement that the loop variable assigns an initial value, and the second expression (integer <= 5) determines whether to loop the expression. The exit status of non 0 o'clock will exit the for loop after performing the command (the for loop condition in C is exactly the opposite). The third expression (integer++) is used to change the statement of a loop variable.

The Sheel does not run as a loop variable with a number of non-integer types, and the default exit state is 0,for ((;;)) when the loop condition is ignored. As a dead loop.

The For loop of Class C calculates the sum of all the odd numbers within the 1~100.

#!/bin/bash

sum=0 for

((i = 1; I <=, i = i + 2)) do
let
     "sum + = i"
done

echo "sum= $s Um

2. While Loop

Also known as the pre-test loop statement, the number of repetitions is the use of a condition to control whether the statement continues to execute repeatedly. In order to avoid the dead loop, it is necessary to ensure that the loop body contains the loop exit condition that the expression has an exit state of 0.

(1) Counter-controlled while loop

#!/bin/bash

sum=0

i=1 while

((i <=)) does
let
     "sum+=i" let
     "i + = 2"   
done

echo " sum= $sum "
Specifies the number of cycles 500, initializes the counter value to 1, and continuously tests whether the loop condition I is less than or equal to 100. The sum of all the odd numbers in the 1~100 is calculated by setting the counter plus the other in the loop condition.

(2) End tag-controlled while loop

Sets a special data value (end tag) to end the while loop.

#!/bin/bash

echo "Please input the num (1-10)"
read num while

[["$num"! = 4]] do 
   if ["$num"-lt 4]
   then
        echo "Too small. Try again! "
        Read num
   elif ["$num"-GT 4]
   then
         echoes "to high. Try again " 
         read num
   else
       exit 0
    fi
do 

echo" congratulation, you are right! "

Example: Using end tag control to implement factorial operations

#!/bin/bash

echo "Please input the num"
read num

factorial=1 while

["$num"-GT 0]
    does let "Factorial= factorial*num" let
    "num--"
do

echo "The factorial is $factorial"

(3) flag-controlled while loop

Use the user-entered flag value to control the end of the loop (avoid conditions that do not know the loop end flag).

#!/bin/bash

echo "Please input the num"
read num

sum=0
i=1

signal=0 while

[["$signal"-ne 1]]< C6/>do
    If ["$i"-eq "$num"] then let 
       "signal=1" Let
       "Sum+=i"
       echo "1+2+...+ $num = $sum"
    else let ' sum=sum+i ' let
       ' i++ '
    fi
done

The flag-controlled while loop evaluates the sum of the 1~n, and the loop variable value is less than 100 to perform the else summation while the loop variable is incremented by 1, until the value of the loop variable equals 100 sets the flag value to 1 and outputs.

The difference between the flag-controlled while loop and the end-tag-controlled while loop is that the user cannot determine that the end flag cannot be determined and the end flag can be determined only after the program runs. They can also be converted to each other.

(4) command-line controlled while loop
Using the command line to specify the output parameters and the number of parameters, usually in conjunction with SHIFT, the shift command makes the position variable move down one ($ $ instead of $, $ $ instead of $ #变量递减), and when the last parameter is displayed to the user, $ #会等于0, $* is also equal to NULL.

#!/bin/bash

echo "Number of arguments is $#"

echoes "What Are You input is:" While

[["$*"! = ""]]
do
  
   echo "$"
    shift
Done
  

The loop condition can be rewritten as while[["$#"-ne 0]], which is equal to 0 o'clock exiting while loop

3. Until cycle

The until command is similar to the while command, while the script until that can be implemented can also be implemented, but the difference is that the exit state of the until loop is not 0 and the exit State is 0 (as opposed to while). That is, the Whie loop resumes execution while the condition is true and until executes the loop when the condition is false.

#!/bin/bash

i=0

until [["$i"-GT 5]] #大于5 do let
    "Square=i*i"
    echo "$i * $i = $square ' Let
    ' I + + "Done

4. Loop nesting

A loop body also contains another complete loop structure, which triggers an internal loop during each execution of the outer loop, and the for, while, and until can be nested with each other.

(1) nested loop implementation 99 multiplication table

#!/bin/bash for

((i = 1; I <=9; i++)) does for
    
    ((j=1; J <= I; j + +)) does let
        "temp = i * j" C14/>echo-n "$i * $j = $temp  "
     done 
     
     Echoes ""   #output newline
done

(2) for loop nesting implementation * Pattern arrangement

#!/bin/bash for

((i=1; I <= 9; i++))
do
    j=9;
    while ((J > I) does
        echo-n "" Let
        "j--" did
    k=1 while
    ((k <= i)) do
        echo-n "*" C12/>let "k++"
    done
    Echoes ""
done

The outer for loop is nested with two inner while loops, where the print space is printed to form a pattern.

5. Loop control break and Continue

If you have to exit the loop, you can use the break loop control, and you can use the Continue loop control if you exit the loop after execution.

(1) Break

Break in the for, while, and until loops can forcibly exit the loop, the break statement can only exit the current loop, and if it is a two-tier loop nesting, you need to use break in the outer loop.

#!/bin/bash

sum=0 for
((i=1; I <=, i++)) do
let 
    "Sum+=i"

    If ["$sum"-GT +]
    Then
        echo "1+2+...+ $i = $sum"
        break
    fi
-Done

(2) Continue

The next loop is executed in the for, while, and until to let the script skip the statement that follows it. The Continue is used to display a number divisible by 7 for 100.

#!/bin/bash

M=1 for
((i=1; i < i++)) does let
    "temp1=i%7"         #被7整除
 
    If ["$temp 1"-ne 0]
    Then
        continue
    fi
    
    echo-n "$i  " let
    
    "temp2=m%7"          #7个数字换一行
    
    if  ["$temp 2"-eq 0]
    then
        Echo '
    fi let
    
    ' m++ "
done"

6. Select Structure

The select structure is not a circular structure from a technical point of view, just similar, it is Bash's extended structure is used for interactive menu display, similar to the case structure of the interaction of case is better.

(1) Select with parameter list

#!/bin/bash

echo "What is your favourite color?"

Select Color in "Red" "Blue" "green" "White" "black" does break did 
    echo "You have

selected $color"

(2) Select without parameter list

The structure passes the list of parameters through the command line and sets the parameter list by the user.

#!/bin/bash

echo "What is your favourite color?"

Select color do break did 
    echo "You have

selected $color"

Iii. Summary

(1) The loop structure is nested into a more complex process, and combined with break and continue can achieve a lot of complex operations.

(2) The syntax that can be combined with other languages helps to better understand the loop structure.

(3) Skilled applications also require a lot of repetitive exercises, and rewriting good shell code is also a good way.

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.