Loop Judgment of shell Script Advancement

Posted by amreiff on Sat, 25 May 2019 01:42:47 +0200

Foreword... 2

I. Conditional Selection and Judgment (if, case). 2

1.1 if statement usage and examples

1.2 case usage and examples

II. Circular Sentences... 7

2.1 for cycle... 8

2.2 while cycle... 10

2.3 until cycle * 12

2.4 select cycle... 13

2.5 Cyclic Supplement.. 14

2.5.1 Loop Control Statement continue&break.14

2.5.2 Loop Control Command Shift 15

2.5.3 Signal Capture trap.16

2.5.4 Create an Infinite Cycle... 18

2.5.5 Executing parallel commands in circular statements

3. Small Supplement... 20 ____________.

1) Print isosceles triangle (with scintillation). 20

2) Print chessboard... 21

 

 

 

 

Preface

In the process of using linux, scripts can save us a lot of time and energy. For example, we need to backup some files regularly. If we do it by hand, we need to do backup every time. If we do something else, what can we do when we forget about it? We can put the backup commands that need to be executed in a script, and use some sentences to judge whether it meets the requirements of our command execution and realize automation 0.0, which saves a lot of time and worry. ~The boss no longer has to worry about me forgetting to backup (). Then, let's share the grammar and examples of the script.

I. Conditional Selection and Judgment (if, case)

1.1 if statement usage and examples

When we encounter the need to judge in the script, we can use the if statement to achieve. The specific grammar is as follows:

  • Single branch

    if judgement condition;

Branch code if the condition is true
  fi

  • Bifurcation

if judgement condition;

Branch code if the condition is true

else

Branch code if the condition is false

fi

  • Multi-branch

if judgment condition 1; then

Branch code if the condition is true
Elf judgment condition 2; then

Branch code if the condition is true
Elf judgment condition 3; then

Branch code if the condition is true

else

All the above conditions are spurious branching codes
fi

In multiple branches, the system will judge the conditions you write one by one. When you first encounter the "true" condition, the branch is executed, and then the entire if statement is terminated.

Note: 1. if and fi appear in pairs

2. if statements can be nested.

Example:

1) Judging the size of two numbers

 1 #!/bin/bash
 2 #Defining variables
 3 read -p "Please input the first num:" num1
 4 read -p "Please input the second num:" num2
 5 #Judging whether the number meets the criteria
 6 if [[ $num1 =~ ^[0-9]+$ && $num2 =~ ^[0-9]+$ ]];then
 7 #    Judge the size of two numbers and output the judgment results
 8     if [ $num1 -lt $num2 ];then
 9         echo "The num2 is biger than the num1"
10     elif [ $num1 -eq $num2 ];then
11         echo "Two numbers equal"
12     else 
13         echo "The num1 is biger than the num2"
14     fi
15 else
16     echo "Please enter the correct number"
17 fi
18 
19 #Delete variables
20 unset num1 num2

 

 

2) Write a script/root/bin/createuser.sh to achieve the following functions: use a user name as a parameter, if the user with the specified parameter exists, it will show its existence, otherwise add it; display the added user id number and other information.

 1 #!/bin/bash
 2 #Defining variables
 3 read -p "Please enter a username:" name
 4 #Determine whether the username exists
 5 if  `id $name &> /dev/null`;then
 6 #    If it exists, it outputs information such as ID, etc.
 7 echo "User exists, user's ID The message is:`id $name`"
 8 else
 9 #    If it does not exist, add the user and set the password to 8 bits at random. The next login prompts you to modify the password and display information such as ID.
10 passwd=`cat /dev/urandom |tr -cd [:alpha:] |head -c8`
11 `useradd $name &> /dev/null`
12 `echo "$passwd" | passwd --stdin $name &> /dev/null`
13 echo "User name: $name Password: $passwd" >> user.txt
14 `chage -d 0 $name`
15 echo "User added, user's ID The message is:`id $name` The password is: $passwd"
16 fi
17 
18 #Delete variables
19 unset name passwd

 

 

1.2 case Usage and Example

When it comes to matching multiple conditions, we may have trouble using if. At this point, we can use case to write this script. The specific grammar of case is as follows:

case variable reference in

PAT1)

Branch 1

;;

PAT2)

Branch 2

;;

...

*)

Default branch

;;

esac

Note: 1. After each branch of case, it ends with two ";" (the last one can be omitted).

2. case and esac appear in pairs

Example:

1) Write a script to prompt the user to enter information and judge that the input is yes or no or other information.

 1 #!/bin/bash
 2 #Defining variables
 3 read -p "Yue ma?(yes or no): " ANS 
 4 #Convert uppercase to lowercase in variables
 5 ans=`echo "$ANS" |tr [[:upper:]] [[:lower:]] `
 6 #Determine what the input information is and output the results
 7 case $ans in
 8 yes|y)
 9     echo "see you tonight"
10     ;;  
11 no|n)
12     echo "sorry,I have no time"
13     ;;  
14 *)
15     echo "what's your means?"
16     ;;  
17 esac
18 
19 #Delete variables
20 unset ANS ans

 

 

2) Write scripts/root/bin/filetype.sh to determine the path of user input files and display their file types (common, directory, links, other file types)

 1 #!/bin/bash
 2 read -p "Please enter a file path:" file
 3 #Determine whether a file exists
 4 `ls $file &> /dev/null`
 5 #If it exists, determine the file type and output it
 6 if [ $? -eq 0 ];then
 7     style=`ls -ld $file | head -c1`
 8     case $style in
 9     -)  
10         echo "This is an ordinary document."
11         ;;  
12     d)  
13         echo "This is a directory file."
14         ;;  
15     l)  
16         echo "This is a link file."
17         ;;
18     *)
19         echo "This is another type of file."
20         ;;
21     esac
22 #If not, prompt and exit
23 else
24     echo "This file does not exist"
25     exit 2
26 fi
27 
28 #Delete variables
29 unset file style

 

 

II. Loop Sentences

In our script, it is certainly necessary to repeat several operations on a piece of code, at which time we will use circular statements. In circular sentences, there are entry and exit conditions, and the number of cycles can be divided into known and unknown (known in advance means we know the specific number of cycles, unknown in advance means that when a certain condition is met, the number of cycles is uncertain.) Next, let's look at the use of circular statements.

2.1 for cycle

The execution mechanism of for loop is to assign the elements in the list to the variable name at one time, and to execute the loop body once after each assignment until the elements in the list are exhausted and the loop ends. There are two basic grammars:

1) for variable name in list; do

Circulatory body

done

Regarding the generation method of the list, the following are:

(1) Give a list directly

(2) Integer list:

(a){start...end}

(b)`seq start end`

(3) Commands returning lists

    $(COMMAND)

(4) Use glob wildcards such as:

      *.sh

Variable Reference

$i,$*

2)for (( exp1; exp2; exp3 )); do

Circulatory body

done

More clearly, you can see from the following picture:

 

Example:

1) Print the Nine-Nine Multiplication Table

 1 #!/bin/bash
 2 #judge i Is the value of 1-9
 3 for i in {1..9};do
 4 #   Determine whether the value of j is 1-$i
 5 for j in `seq 1 $i`;do
 6 #       If yes, print i*j Value
 7         echo -en "$i*$j = $[$i*$j]\t" 
 8     done
 9     echo
10 done
11 
12 #Delete variables
13 unset i j

 

 

2) Input positive integer n, calculate 1+... The sum of +n

 1 #!/bin/bash
 2 #Defining variables
 3 sum=0
 4 read -p "Please enter a positive integer:" num 
 5 #Determine whether num is a positive integer?
 6 if [[ $num =~ ^[[:digit:]]+$ ]];then
 7 #   If so, when i is between 1-$num, output the sum value
 8     for i in `seq 1 $num`;do
 9         let sum+=$i    
10     done 
11         echo "sum=$sum"
12 #If not, prompt for positive integer output
13 else 
14     echo "Please enter a positive integer!"
15 fi
16 
17 #Delete variables
18 unset i sum num

 

 

2.2 while loop

The while loop is slightly more complex than the for loop. The specific grammar is as follows:

while CONDITION; do

Circulating body

done

Note: 1. Entry condition: CONDITION is true; Exit condition: CONDITION is false.

2. CONDITION is the cycle control condition: before entering the cycle, make a judgment first; after each cycle, make a judgment again; if the condition is "true", then execute a cycle; know that the condition test state is "false" to terminate the cycle.

3. CONDITION should generally have a loop control variable; the value of this variable will be constantly revised in the loop body.

Example:

1) Calculate the sum of all positive and odd numbers within 100

 1 #!/bin/bash
 2 #Defining variables
 3 i=1
 4 sum=0
 5 #When I < 100, execute the following statement
 6 while [ $i -le 100 ];do
 7 #When i For odd numbers, another sum=sum+I,i=i+1
 8     while [ $[i%2] -eq 1 ];do
 9         let sum+=$i
10         let i+=1 
11 done
12 #   When i When not an odd number, i=i+1
13     let i+=1
14 done
15 #Output result
16 echo "sum=$sum"
17 
18 #Delete variables
19 unset i sum

 

 

2.3 until cycle

The syntax of until loops is similar to that of while, but the conditions for entry and exit are just the opposite, so they are not often used as long as we understand them. The specific grammar is as follows:

until CONDITION; do

Circulating body

done

Note: 1. Entry condition: CONDITION is false; Exit condition: CONDITION is true.

2. do and done appear in pairs.

Example:

1) Cyclic output 1-10

 1 #!/bin/bash
 2 #Defining variables
 3 i=1
 4 #When I > 10, exit the loop
 5 until [ $i -gt 10 ];do
 6 #   output i The value of i=i+1
 7     echo $i 
 8     let i+=1
 9 done
10 
11 #Delete variables
12 unset i 

 

2.4 select cycle

select loops are mainly used to create menus. Menu items arranged in numerical order will be displayed on standard errors, and PS3 prompts will be displayed, waiting for user input.

The user enters a number in the menu list and executes the corresponding command.

User input is stored in the built-in variable REPLY.

The specific grammar of select is as follows:

select variable in list; do

Circular body command

done

Note: 1. select is a wireless loop, so remember to exit the loop with the break command or terminate the script with the exit command. You can also press ctrl+c to exit the loop.

select is often used in combination with case.

(3) Similar to for loops, in-list can be omitted and location variables are used.

Example:

1) Generate a menu and display the selected price.

 1 #!/bin/bash
 2 #Define the PS3 prompt
 3 PS3="Please choose the menu: "
 4 #Output menu
 5 select menu in yangroutang mifan hulatang jiaozi lamian huimian quit
 6 do
 7 #   Judgement and choice
 8     case $REPLY in
 9     1|4)
10         echo "The price is 20"
11         ;;  
12     2|5)
13         echo "The price is 12"
14         ;;  
15     3|6)
16         echo "The price is 10"
17         ;;  
18     7)  
19         break
20         ;;  
21     *)  
22         echo "Choose error"
23         ;;  
24     esac
25 done

 

2.5 Cyclic Small Supplement

2.5.1 Loop Control Statement continue & break

Loop control statements are used in the loop body. There are two kinds of common control statements, continue and break. Next, let's look at the difference between the two.

The continue statement ends this cycle and goes directly to the next round of judgment; the innermost layer is the first.

The break statement ends with the entire loop, with the innermost layer being Layer 1.

Example:

1) Seek (1 + 3 +... +49+53+... Sum of +99)

 1 #Defining variables
 2 sum=0
 3 for ((i=1;i<=100;i++));do
 4 #   When i is odd, continue executing
 5     if [ $[i%2] -eq 1 ];then
 6 #       When i=51, skip the loop
 7         if [ $i -eq 51 ];then
 8             continue
 9         fi  
10         let sum+=$i
11     fi  
12 done
13 echo "sum=$sum"
14 
15 #Delete variables
16 unset i sum

 

2) Seek (1 + 3 +... Sum of +49)

 1 #!/bin/bash
 2 #Defining variables
 3 sum=0
 4 for ((i=1;i<=100;i++));do
 5 #   When i is odd, continue executing
 6     if [ $[i%2] -eq 1 ];then
 7 #       When i=51, jump out of the loop
 8         if [ $i -eq 51 ];then
 9             continue
10         fi  
11         let sum+=$i
12     fi  
13 done
14 echo "sum=$sum"
15 
16 #Delete variables
17 unset i sum

 

2.5.2 Circular Control Command shift

Position parameters can be shifted to the left using the shift command, such as shift 3 to indicate that the original $4 is now $1, the original $5 is now $2 and so on, the original $1, $2, $3 is discarded, and $0 is not moved. The shift command without parameters is equivalent to shift 1.

We know that for location variables or command-line parameters, the number must be determined, or when the shell program does not know the number, all parameters can be assigned to the variable $*. When the user asks the shell to process the parameters one by one without knowing the number of location variables, that is, $2 after $1. The value of variable $1 before the shift command is executed is not available after the shift command is executed.

Example:

1) Test shift command

1 #!/bin/bash
2 until [ $# -eq 0 ];do
3     echo "The first argument is:$1,The number of arguments is:$#"
4     shift
5 done

 

2.5.3 signal capture trap

Trap is a shell built-in command that specifies how signals are handled in scripts. For example, pressing Ctrl+C will terminate the execution of the script. In fact, the system sends SIGINT signal to the script process. The default processing method of SIGINT signal is to exit the program. If you want Ctrl+C not to quit the program, you have to use the trap command to specify how SIGINT is handled. The trap command not only handles Linux signals, but also specifies how to handle script exits (EXIT), debugging (DEBUG), errors (ERR), and returns (RETURN).

The basic format grammar is as follows:

  • trap'trigger Instruction'signal

When the custom process receives the specified signal from the system, it will execute the trigger instruction instead of the original operation.

  • trap''signal

Neglect signal operation

  • trap'-'signal

Operation of restoring the original signal

  •        trap -p

List the operations of the custom signal, that is, to indicate what trap operations are currently in use.

Note: 1. Signal representation: It can be a complete signal/abbreviation/number (specific content is queried by kill-l)

(2) Signal 9, mandatory killing, not capture.

Example:

1) Print 0-9, ctrl+c termination invalid

1 #!/bin/bash
2 #Setting up signal acquisition
3 trap 'echo press ctrl+c' 2
4 for ((i=0;i<10;i++));do
5     sleep 1
6     echo $i
7 done


2) ctrl+c cannot be terminated before printing 0-9, 3, and can be terminated after resuming 3.

 1 #!/bin/bash
 2 #Setting up signal acquisition
 3 trap '' 2
 4 trap -p
 5 for ((i=0;i<3;i++));do
 6     sleep 1
 7     echo $i
 8 done
 9 trap '-' SIGINT
10 for ((i=3;i<10;i++));do
11     sleep 1
12     echo $i
13 done


2.5.4 Create an Infinite Cycle

In our shell script, we can create a dead loop, which is set as follows:

   while true;do

Circulating body

   done

 

2.5.5 Executing Parallel Commands in Loop Statements

When we need to execute a command many times in a script, we can set it to execute in parallel, which can greatly improve the speed of the script, but there are also shortcomings. Parallel execution is equivalent to opening a lot of sub-shell s to execute together, running speed up, but the consumption of resources has increased.

Examples of specific uses are as follows:

for name in list; do

     {

Circulator

}$

   done

   wait

Example:

1) Search the ip address of up in the segment of ip (subnet mask is 24) designated by oneself.

 1 #!/bin/bash
 2 #Defining variables
 3 read -p "Please input network (eg:172.17.0.1): " net echo $net |egrep -o "\<(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>"
 4 #Judging whether network segments conform to specifications
 5 [ $? -eq 0 ] || ( echo "input error";exit 10 )
 6 #Determine which IP can be ping-connected and executed in parallel within a network segment
 7 IP=`echo $net |egrep -o "^([0-9]{1,3}\.){3}"`
 8 for i in {1..254};do
 9      {   
10          ping -c 1 -w 1 $IP$i &> /dev/null && \
11          echo "$IP$i is up" 
12      }&  
13 done
14 wait
15  
16 #Delete variables
17 unset net IP i

 

3. Small Supplement

So many grammars are introduced, let's have some fun. ~Below are some interesting scripts for you to share

1) Print isosceles triangle (with scintillation)

 1 #!/bin/bash
 2 #num = total line number i = which line j = number k = number of spaces
 3 read -p "Please enter a number:" num 
 4 for i in `seq 1 $num`;do
 5     for k in `seq 1 $[$num-$i]`; do
 6         echo -n " "
 7     done
 8     for j in `seq 1 $[2*$i-1]`;do
 9         if [ $j -eq 1 ] || [ $j -eq $[2*$i-1] ] || [ $i -eq $num ];then
10             color=$[RANDOM%5+31]
11             echo -en "\033[1;$color;5m*\033[0m"
12         else
13             echo -n "*"
14         fi  
15     done
16     echo
17 done
18 
19 #Delete variables
20 unset num i j k color

The specific effect you can try on your own is the effect of the following two pictures:


2) Printing chessboard

 1 #!/bin/bash
 2 #Defining variables
 3 color_1="\033[1;44m  \033[0m"
 4 color_2="\033[1;45m  \033[0m"
 5 for (( i=1;$i <=8;i++ ));do
 6     for (( j=1;$j <=8;j++ ));do
 7         if [ $[$i%2] == 1 ] && [ $[$j%2] == 1 ];then
 8             echo -en "$color_1$color_2"
 9         elif [ $[$i%2] == 0 ] && [ $[$j%2] == 0 ];then
10             echo -en "$color_2$color_1"
11         fi  
12     done
13     echo
14 done
15 
16 #Delete variables
17 unset color_1 color_2 i j

Specific colors can be adjusted according to your preferences.~

Topics: Linux shell network