Loop Statement of Linux Shell Script

1. echo

echo -n // means no newline output

echo -e //Output escape characters, and output the escaped content to the screen

Common escape characters

Escape Symbol Meaning

-n means no newline output

\e output escape character, output the escaped content to the screen

\b After escaping, it is equivalent to pressing the backspace key, but the premise is that there are characters after b: b means to delete the previous character, \b\b means to delete the first two characters

\c No newline output, when there are characters behind \c, the following characters will not be output

\
Newline, the output character starts a new line except \

\f or \v Newline, but the beginning of the newline after the newline is connected to the end of the previous line

\t After turning, it means inserting a tab, that is, a horizontal tab

\r Move the cursor to the beginning of the line, and overwrite the previous characters of equal length with the following characters

2. for loop

Read different variable values to execute the same set of commands one by one

The for loop is often used when you already know how many times to loop

Format

for variable name in list of values

do

command sequence

done

Example 1

vim a.sh #Create script a.sh
Script content:
#!/bin/bash
for i in {1..5} #for loop 5 times, i=1 for the first time, i=2 for the second time and so on until i=5
do
echo "$i" #Loop action, output $i each time
done #for statement end flag
bash a.sh #call the shell to execute the script a.sh
Results of the:
1
2
3
4
5

Example 2

vim a.sh
Script content:
#!/bin/bash
for(( i=0;i<=5;i ++ )) #Define the initial value of the variable i in the for loop is 0, the loop condition i is less than or equal to 5, and i increments by 1 every loop
do
echo "$i" #for loop executes once per loop to output $i
done #for statement end flag
bash a.sh #call the shell to execute the script
Output result:
0
1
2
3
4
5

3.while

Repeatedly test a condition and execute it repeatedly as long as the condition is true

Often established when the range is not known

Format

while conditional test operation

do

command sequence

done

Example:

vim b.sh #Create script b.sh
Script content:
#!/bin/bash
i=0
while [ $i -le 5 ] #Execute while loop when variable i is less than or equal to 5
do
echo "$i" #Cycle execution content, print $i every cycle
let i + + #Calculate i once per cycle + + i itself + 1
done #while statement end flag
sh b.sh #call bash to execute b.sh script
Results of the:
0
1
2
3
4

infinite loop statement

while [1 -eq 1] Judgment condition Write a condition that is always true
   do always execute the command in do
   done
while true directly write the judgment condition is true
   do always execute the command in do
   done
while : The judgment condition is a colon also means an infinite loop
   do always execute the command in do
   done

4. until

Repeatedly test a certain condition, as long as the condition is not true, it will be executed repeatedly

Format

until conditional test operation

do

command sequence

done

Example:

[root@localhost opt]# vim until.sh
i=1
until [ $i -gt 10 ]
do
echo $i
let i++
done

5. Break out of the loop

1. continue jumps out of the loop

Indicates to jump out of the loop when the continue condition is met, but it does not affect the execution of subsequent loops

Example:

vim a.sh #Create script a.sh
#! /bin/bash
for i in {1..5} #for loop 5 times from i=1 to i=5
do
if [ $i -eq 3 ] #if judgment statement, if $1 is equal to 3, then execute the content of then
then
continue #Jump out of the loop when $i=3 but does not affect the following loop
fi # end if statement
echo "$i" # output $i once without executing a for loop
done #for loop end statement
sh a.sh #call the shell to execute the script
output result
1
2
4
5

break out of the loop

When a break is encountered in a loop, it ends the loop directly, but does not affect the outer nested loop.

break [Number] End several loops in the number, if it is 2, it will end its own loop and the outer nested loop, if it is 3, it will end its own loop and the outer nested 2 loops

Example:

vim a.sh #Create a.sh script
#!/bin/bash
for j in {1..3} #The first layer of for loop, j=1, 2, 3 execute the content of do once each
do #Execution content of the first layer of for loop
    for i in {1..5} #The second layer of for loop, i=1, 2, 3, 4, 5 execute the content of do once each
    do #execution content of the second layer for loop
        if [ $i -eq 3 ] #The if judgment statement added in the second layer of for loop, when $i=3 is to execute then content
        then
        break #The second layer of for loop judgment statement executes the command, break ends the loop
        fi #end of if statement
    echo "$i" #The second layer of for loop statement executes each loop to output $i
    done #The end sign of the second layer of for loop statement
done #The end sign of the first layer of for loop statement
sh a.sh #call bash to execute a.sh script
1
2
1
2
1
2

Classic common examples

  1. Loop printing 9*9 multiplication table

vim 99.sh #edit 99.sh script
#!/bin/bash
for j in {1..9} #The content of the column loop remains unchanged
do
    for i in `seq $j`
    do
    echo -ne "$j*$i=$[ $j*$i ]\t" #The output content of the line is changed to 9*9 formula and result. $[ ] represents the positive integer knot in the calculation
                              If the echo -e parameter indicates the call escape character, \t indicates a tab character, that is, output a tab key when looping
    done
echo
done
bash 99.sh #call the shell to execute the script
Output result:
1*1=1
2*1=22*2=4
3*1=33*2=63*3=9
4*1=44*2=84*3=124*4=16
5*1=55*2=105*3=155*4=205*5=25
6*1=66*2=126*3=186*4=246*5=306*6=36
7*1=77*2=147*3=217*4=287*5=357*6=427*7=49
8*1=88*2=168*3=248*4=328*5=408*6=488*7=568*8=64
9*1=99*2=189*3=279*4=369*5=459*6=549*7=639*8=729*9=81
  1. Loop ping to test the network connectivity of a network segment

vim ping.sh #Create ping.sh script
Script content:
#!/bin/bash
read -p "Please enter the network segment to be tested, the format is (192.168.233.):" ip #Read user input as variable ip
for i in {1..254} #for loop 254 times, starting from i=1
do
{ # Treat {} content as a whole
ping -c2 -w2 $ip$i & amp;>/dev/null #Specify ping packets with 2 timeouts and end time of 2 seconds and put all the generated content into the null trash can, the & amp; symbol indicates error output also put in null
    if [ $? -eq 0 ] #if condition judges if the command executed in the previous cycle is correct, then $? Return 0, if it is equal to 0, execute the content of then
    then
    echo "$ip$i is online" #if the condition is met, execute printing
    echo $ip$i >> host.txt #Append the ip where the if condition is true to the host.txt file
    else
    echo "$ip$i is offline" #if the added judgment is not established, execute printing
    the fi
} & amp; #Put the contents of the cycle into the background for execution
done
wait #Exit without waiting at the end of execution

3. While the infinite loop realizes the number guessing game

Requirement: Generate a random price of 1-100 for the user to guess until the guess is right and end the game, and count how many times the user guesses correctly

vim game.sh #Create script game.sh
Script content:
#!/bin/bash
num=`echo $[RANDOM 0 + 1]` # $[RANDOM] is a 0-32767 random number, 0 + 1 divided by 100 to take the remainder + 1 means to generate a 0-100 random number
time=0 #Define the number of correct guesses variable time initial value is 0
while true #Generate while infinite loop
do #The loop action is the content in do
let time + + #The time variable is incremented by 1 every cycle
read -p "Please enter the number you guessed, range (1-100):" user #read the content entered by the user as the variable user
    if [ $user -eq $num ] #Conditional judgment branch 1, if the user input is equal to random generation, execute then action
    then
    echo "You guessed right, you have guessed $time times in total" #if branch 1 condition is established and execution output
    break #if branch 1 condition is met, then end this loop
    elif [ $user -gt $num ] #Conditional judgment branch 2, if the user input is greater than random generation, execute this then action
    then
    echo "You guess big, please guess small" #Condition judgment branch 2 is established to prompt the user to guess big
    elif [ $user -lt $num ] #Conditional judgment branch 3, if the user input is less than random generation, execute this then action
    then
    echo "Your guess is small, please go to big guess" #Condition judgment branch 3 is established to prompt the user to guess small
    fi #end of if statement
done
sh game.sh #call bash to execute the script