Linux operating system experiment seven Shell programming cycle program programming

1. Experimental purpose and requirements

  1. Master the use of the for statement
  2. Master the use of while, continue, until statements
  3. Master the use of loop statements
  4. Familiar with the nesting of loop statements

2. Experimental platform

The experimental environment installed in the laboratory (Linux operating system) and Touge (www.educoder.net) experimental platform (course experiment)

3. Experimental content

  1. Practice using the for statement
  2. Practice the use of while, continue, until statements
  3. Practice nesting of loop statements

4. Experiment details and steps

mission details

The task of this level: master the for loop statement and the use of the seq command in the for loop.

related information

In actual programming, a set of commands needs to be repeated until a certain condition is reached, such as processing all files in a directory, all users on the system, or all lines in a text file. Therefore, statements such as for loops, while loops, and util loops were born. This level first introduces the use of the for loop statement.

Basic syntax of for loop:
  1. for var in item1 item2 ... itemN
  2. do
  3.     command1
  4.     command2
  5.     ...
  6.     commandN
  7. done

or as a single line:

  1. for var in item1 item2 ... itemN; do command1; command2… done;
For loop syntax evolution:

[Syntax 1] Traversing a common list, the items separated by spaces in the shell will be regarded as a list by default.

  1. for variable in value1 value2 value3..
  2.   do
  3.    block
  4.   done

[Example 1] Output uptime five times:

  1. #!/bin/bash
  2. for i in 1 2 3 4 5 
  3. do 
  4.   echo "$i-->$(uptime)"
  5. done

The output is as follows:

  1. [root@master-01-k8s opt]# bash a.sh
  2. 1--> 16:34:39 up 236 days, 23:41,  2 users,  load average: 0.53, 0.46, 0.49
  3. 2--> 16:34:39 up 236 days, 23:41,  2 users,  load average: 0.53, 0.46, 0.49
  4. 3--> 16:34:39 up 236 days, 23:41,  2 users,  load average: 0.53, 0.46, 0.49
  5. 4--> 16:34:39 up 236 days, 23:41,  2 users,  load average: 0.53, 0.46, 0.49
  6. 5--> 16:34:39 up 236 days, 23:41,  2 users,  load average: 0.53, 0.46, 0.49

[Syntax 2] for traverses the "array of results returned by the command", backticks ` ` or $()means the list of results returned by the command.

  1. for variable in `command`
  2.   do
  3.    block
  4.   done

[Example 2] Traverse the files in the /home directory.

  1. #!/bin/bash
  2. for i in $(ls /home)       
  3. do
  4.    echo "The file in the current directory is $i"
  5. done

The output is:

  1. The file in the current directory is admin
  2. The file in the current directory is aliyun
  3. The file in the current directory is aliyun_metric-server2.yaml
  4. The file in the current directory is git
  5. The file in the current directory is pdl
  6. The file in the current directory is prometheus
  7. The file in the current directory is work
  8. The file in the current directory is zsp

[Grammar 3] Loop statement in c language style:

  1. #!/bin/bash
  2. for (( initial value; loop control; variable change))
  3. do
  4.   block
  5. done

The shell's for command is similar to the C language, with a specific method for specifying variables, a condition that must remain true for iteration to continue, and another method for changing the variable on each iteration. The for loop stops when the specified condition is not true. Conditional equations are defined using standard mathematical notation.

【Example 3】

  1. #!/bin/bash
  2. # Note that there is a space around the double brackets; i=1 is a variable assignment, no more spaces
  3. for (( i=1; i <= 10; i++ )) 
  4. do
  5.     echo "The next number is $i"
  6. done

This code produces a simple iterative loop with the variable i as the counter. The first part assigns a default value to the variable; the middle part defines the condition for loop repetition. When the defined condition is not true, the for loop stops iterating; the last part defines the iteration process. After each iteration, the expressions defined in the last section are executed. In this example, the i variable is incremented by 1 after each iteration. Results of the:

  1. The next number is 1
  2. The next number is 2
  3. The next number is 3
  4. The next number is 4
  5. The next number is 5
  6. The next number is 6
  7. The next number is 7
  8. The next number is 8
  9. The next number is 9
  10. The next number is 10
seq command

The seq command is used to generate a list of all integers from one number to another. Common usage is as follows:

  1. seq [options]... Mantissa
  2. seq [options]... the first number and the last number
  3. seq [options]... initial increment mantissa

[Example 4] Use the seq command, combined with the for loop, to print all the integers between 1 and 10.

  1. for i in `seq 1 10`
  2. do
  3.     echo "The number $i is $i"
  4. done

The output is as follows:

  1. The first number is 1
  2. 2nd number is 2
  3. The 3rd number is 3
  4. The 4th number is 4
  5. The 5th number is 5
  6. The 6th number is 6
  7. The 7th number is 7
  8. The 8th number is 8
  9. The 9th number is 9
  10. The 10th number is 10

programming requirements

Supplement the code in the Begin-End interval of the editor on the right, and use the for loop and the seq command to print odd numbers between 1 and 10.

mission details

The task of this level: Master the usage of while command.

related information

three operators
  • Double parentheses (( ))are commands specially used for integer calculation in Bash Shell. It is highly efficient and flexible in writing. It is a commonly used calculation command in enterprise operation and maintenance. Please refer to Figure 1 for specific usage;
  • []It is a shell built-in keyword, which is similar to the test command and can be used to determine whether a certain condition is true. Tests available for strings, values ​​and files;
  • [[ ]]It is a shell built-in keyword, which is similar to the test command and is also used to check whether a certain condition is true. Compared with [], [[]]it is more powerful and supports regular expressions and logical operations.
while loop syntax

The while loop is the simplest loop in Shell scripts. When the condition is met, while executes a set of statements repeatedly; when the condition is not met, it exits the while loop.

The while loop is used as follows:

  1. while condition # Here condition can be (()), [], [[]] judgment result
  2. do
  3.     statements
  4. done

Grammar description: condition indicates the judgment condition, statements indicates the statement to be executed (there may be only one statement or multiple statements), and both do and done are keywords in the shell.

The execution flow of the while loop is:

  • First judge the condition, if the condition is true, enter the loop and execute the statements in the while loop body, that is, the statements between do and done. This completes a cycle;
  • Every time it is executed to done, it will re-judge whether the condition is true. If it is true, it will enter the next loop and continue to execute the statement between do and done; if it is not true, it will end the whole while loop and execute other shell codes after done;
  • If the condition is not established at the beginning, the program will not enter the loop body, and the statements between do and done will not have a chance to be executed.

Note: There must be corresponding statements in the body of the while loop to make the condition more and more close to "failure". Only in this way can the loop finally exit, otherwise the while loop will become an endless loop and will continue to execute forever.

[Example 1] Add system load information to the /opt/uptime.log file every two seconds.

  1. #!/bin/bash
  2. while [ 1 ] # [ 1 ] is the same as true, but the first two sides need to have spaces
  3. do
  4.         uptime >>/tmp/uptime.log # >> is a redirection symbol
  5.         sleep 2
  6. done
  7. #Note:
  8. #uptime for viewing system load
  9. #sleep 2 means the program sleeps for one second

【Example 2】Calculate the sum of 1+2...100.

  1. method one:
  2. #!/bin/sh
  3. SUM=0
  4. I=1
  5. while [ $I -le 100 ] #[] requires the variable value symbol "$", and only "-le" can be used for greater than or less than
  6. do
  7.         ((SUM+=I))
  8.         let I++
  9. done
  10. echo $SUM
  11. -------------------------------------------------------------------------------------------------
  12. Method 2:
  13. #!/bin/sh
  14. SUM=0
  15. I=1
  16. while ((I<=100)) #(()) can not use the variable value symbol, greater than or less than can be used directly
  17. do
  18.         ((SUM+=I))
  19.         ((I++))
  20. done
  21. echo $SUM
  22. -------------------------------------------------------------------------------------------------
  23. Method 3:
  24. #!/bin/sh
  25. SUM=0
  26. I=100
  27. ((SUM=I*(I+1)/2))
  28. echo $SUM
Loop interrupted and non-interrupted

When some programs are executed, the user expects the program to run all the time. When running the script in [Example 1], we can use sh shell.sh & instead to sh shell.sh keep it running in the background. When we encounter a script infinite loop, we can also use Ctrl+z to force a break. Commonly used interruption and non-interruption techniques are as follows:

  1. Use the "sh shell.sh &" command, that is, use & to run in the background
  2. Use the "nohup shell.sh &" command, that is, use nohup plus & to run the script in the background
  3. Use the screen to keep the session, and then execute the script, that is, use the screen to keep the current session
  4. Knowledge of running in the background:
  5. sh shell.sh & script shell.sh is executed in the background
  6. Ctrl+c stop executing the current script or task
  7. Ctrl+z suspends the execution of the current script
  8. jobs View currently executing scripts or tasks
  9. bg Put the current script or task in the background for execution
  10. kill closes the current script task, that is, closes the process in the form of "kill % number", and the task number is obtained through jobs
  11. fg puts the current script or task in the foreground for execution, if there are multiple tasks, "fg number" calls out the corresponding task number

[Example 3] The actual operation effect is as follows:

  1. [centos@mycentos shell]$ sh 2.sh & # running in the background
  2. [1] 2988
  3. [centos@mycentos shell]$ jobs #View the number of tasks
  4. [1]+  Running                 sh 2.sh &
  5. [centos@mycentos shell]$ kill %1 #Close the process whose process is 1
  6. [centos@mycentos shell]$ jobs      
  7. [1]+ Terminated sh 2.sh #The program has been closed

You can try it yourself on the command line according to Example 3.

mission details

The task of this level: master the use of the until loop statement.

related information

until statement syntax

The unti loop is just the opposite of the while loop; the loop is executed when the judgment condition is not true, and the loop is terminated once the judgment condition is true. The syntax is as follows:

  1. until condition
  2. do
  3.     statements
  4. done

Like while, condition indicates the judgment condition, statements indicates the statement to be executed (there may be only one or multiple statements), and both do and done are keywords in the Shell.

The execution flow of the until loop is:

  • First judge the condition, if the condition is not true , enter the loop and execute the statement in the until loop body (the statement between do and done), thus completing a loop;
  • Every time it is executed to done, it will re-judge whether the condition is true. If not, enter the next loop and continue to execute the statements in the loop body; if it is true, end the entire until loop and execute other shell codes after done;
  • If the condition is established at the beginning, the program will not enter the loop body, and the statements between do and done will not have a chance to be executed.

Note: There must be corresponding statements in the body of the until loop to make the condition more and more close to "established" . Only in this way can the loop finally exit, otherwise until will become an endless loop and will continue to execute forever.

【Example 1】

  1. #!/bin/bash
  2. i=0
  3. until [[ "$i" -gt 5 ]] #greater than 5
  4. do
  5.     let "square=i*i"       
  6.     echo "$i * $i = $square"
  7.     let "i++"
  8. done

Execution process: until i is greater than 5, the loop exits; when the variable i is less than or equal to 5, execute the commands in the do and done code blocks, where let is the built-in calculation command of the shell. The input and output results are as follows:

  1. [root@work02 opt]# bash a.sh
  2. 0 * 0 = 0
  3. 1 * 1 = 1
  4. 2 * 2 = 4
  5. 3 * 3 = 9
  6. 4 * 4 = 16
  7. 5 * 5 = 25

mission details

The task of this level: master the method and usage scenarios of loop nesting in shell statements, and output executable files in the system.

related information

Loop statements can use any type of command within the loop, including other loop commands. This kind of loop is called a nested loop. Note that when using nested loops, you are using iteration within iteration, which is a product of the number of times the command is run. Failure to pay attention to this can cause problems in scripts.

for-for loop nesting

Here's a simple example of nesting for loops within for loops.

【Example 1】

  1. #!/bin/bash
  2. # nesting for loops
  3. for (( a = 1; a <= 3; a++ ))
  4. do
  5.  echo "Starting loop $a:"
  6.  for (( b = 1; b <= 3; b++ ))
  7.  do
  8.  echo " Inside loop: $b"
  9.  done
  10. done

The output of executing the script is:

  1. Starting loop 1:
  2.  Inside loop: 1
  3.  Inside loop: 2
  4.  Inside loop: 3
  5. Starting loop 2:
  6.  Inside loop: 1
  7.  Inside loop: 2
  8.  Inside loop: 3
  9. Starting loop 3:
  10. Inside loop: 1
  11. Inside loop: 2
  12. Inside loop: 3

This nested loop (also known as the inner loop) iterates over all of its values ​​once per iteration of the outer loop. Note that there is no difference between the do and done commands of the two loops. The bash shell knows that when the first done command executes, it refers to the inner loop and not the outer loop.

for-while loop nesting

The same is true when mixing loop commands, such as placing a for loop inside a while loop.

【Example 2】

  1. #!/bin/bash
  2. # placing a for loop inside a while loop
  3. var1=5
  4. while [ $var1 -ge 0 ]
  5. do
  6.  echo "Outer loop: $var1"
  7.  for (( var2 = 1; $var2 < 3; var2++ ))
  8.      do   
  9.          var3=$[ $var1 * $var2 ]
  10.          echo " Inner loop: $var1 * $var2 = $var3"
  11.      done
  12. var1=$[ $var1 - 1 ]
  13. done

The output of executing the script is:

  1. Outer loop: 5
  2.  Inner loop: 5 * 1 = 5
  3.  Inner loop: 5 * 2 = 10
  4. Outer loop: 4
  5.  Inner loop: 4 * 1 = 4
  6.  Inner loop: 4 * 2 = 8
  7. Outer loop: 3
  8.  Inner loop: 3 * 1 = 3
  9.  Inner loop: 3 * 2 = 6
  10. Outer loop: 2
  11. Inner loop: 2 * 1 = 2
  12. Inner loop: 2 * 2 = 4
  13. Outer loop: 1
  14. Inner loop: 1 * 1 = 1
  15. Inner loop: 1 * 2 = 2
  16. Outer loop: 0
  17. Inner loop: 0 * 1 = 0
  18. Inner loop: 0 * 2 = 0
until-while loop nesting

If you really want to challenge your brain, you can mix until and while loops. 【Example 3】

  1. #!/bin/bash
  2. # using until and while loops
  3. var1=3
  4. until [ $var1 -eq 0 ]
  5. do
  6.      echo "Outer loop: $var1"
  7.      var2=1
  8.      while [ $var2 -lt 5 ]
  9.          do
  10.              var3=$(echo "scale=4; $var1 / $var2" | bc)
  11.              echo " Inner loop: $var1 / $var2 = $var3"
  12.              var2=$[ $var2 + 1 ]
  13.          done
  14.      var1=$[ $var1 - 1 ]
  15. done

The output of executing the script is:

  1. Outer loop: 3
  2.  Inner loop: 3 / 1 = 3.0000
  3.  Inner loop: 3 / 2 = 1.5000
  4.  Inner loop: 3 / 3 = 1.0000
  5.  Inner loop: 3 / 4 = .7500
  6. Outer loop: 2
  7.  Inner loop: 2 / 1 = 2.0000
  8.  Inner loop: 2 / 2 = 1.0000
  9.  Inner loop: 2 / 3 = .6666
  10. Inner loop: 2 / 4 = .5000
  11. Outer loop: 1
  12. Inner loop: 1 / 1 = 1.0000
  13. Inner loop: 1 / 2 = .5000
  14. Inner loop: 1 / 3 = .3333
  15. Inner loop: 1 / 4 = .2500

The outer until loop starts with a value of 3 and continues until the value equals 0. The inner while loop starts with a value of 1 and executes as long as the value is less than 5. Each loop must change the value used in the test condition, otherwise the loop would go on endlessly.

control loop

You might think that once you start the loop, you have to wait until the loop completes all iterations, but that's not the case. There are two commands that can help us control what happens inside the loop: the break command and the continue command, each of which has a different usage in how to control the execution of the loop. How to use these commands to control the loop is described below.

  • break command : jump out of a single loop When the shell executes the break command, it will try to break out of the currently executing loop, see 【Example 4】.

【Example 4】

  1. #!/bin/bash
  2. # breaking out of a for loop
  3. for var1 in 1 2 3 4 5 6 7 8 9 10
  4. do
  5.      if [ $var1 -eq 5 ];then
  6.          break
  7.      fi
  8.     echo "Iteration number: $var1"
  9. done
  10. echo "The for loop is completed"

The output of executing the script is:

  1. Iteration number: 1
  2. Iteration number: 2
  3. Iteration number: 3
  4. Iteration number: 4
  5. The for loop is completed

A for loop typically iterates over all values ​​specified in a list. But when the condition of if-then is satisfied, the shell will execute the break command to stop the for loop.

  • continue command : The continue command can terminate the commands in a loop in advance, but it will not completely terminate the entire loop. You can set conditions inside the loop under which the shell does not execute the command. Here is a simple example of using the continue command in a for loop.

【Example 5】

  1. #!/bin/bash
  2. # using the continue command
  3. for (( var1 = 1; var1 < 15; var1++ ))
  4. do
  5.      if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
  6.          then
  7.          continue
  8.      fi
  9.      echo "Iteration number: $var1"
  10. done

The output of executing the script is:

  1. Iteration number: 1
  2. Iteration number: 2
  3. Iteration number: 3
  4. Iteration number: 4
  5. Iteration number: 5
  6. Iteration number: 10
  7. Iteration number: 11
  8. Iteration number: 12
  9. Iteration number: 13
  10. Iteration number: 14

Execution instructions:

  • When the condition of the if-then statement is met (the value is greater than 5 and less than 10), the shell will execute the continue command, skipping the remaining commands in this cycle, but the entire cycle will continue. When the condition of the if-then is no longer met, everything is back on track;
  • You can also use the continue command in while and until loops, but be careful. Remember, when the shell executes the continue command, it skips the remaining commands. Problems can arise if you increment the test condition variable inside one of the conditions.

programming requirements

Background: When you run a program from the command line, the Linux system searches a series of directories to find the corresponding file.

Supplement the code in the Begin-End section of the editor on the right, and output the executable files of the variable dir.

Programming ideas:

  • The first is to create a for loop that iterates through the directories in the environment variable dir. Don't forget to set the IFS separator when processing. ( IFS=, that is, the separator of the specified shell is  )
    • i. IFS=:
    • ii. for folder in $dir
    • iii. do
  • Now that you have the individual directories in variables  $folder , you can use another for loop to iterate over all the files in a particular directory.
    • i. for file in $folder/*
    • ii. do
  • The last step is to check whether each file has executable permissions, you can use the if-then test function to achieve.
    • i. if [ -x $file ]
    • ii. then
    • iii. echo " $file"
    • iv. be

mission details

The task of this level: Use the for loop to print 5 lines of @ that meet the requirements: the first line prints 1 @, the second line prints 2 @, the third line prints 3 @, the fourth line prints 4 @, and the fourth line prints 4 @. 5 lines print 5 @.

related information

In order to complete the task of this level, you need to master: the basic statement format of the for loop.

Case Demo 1

Suppose there are 4 students, namely Zhang San, Li Si, Wang Wu, and Zhao Liu. If each line is output in the style of "student:...", you can write the program as follows:

  1. #!/bin/bash
  2. for stud in Zhang San Li Si Wang Wu Zhao Liu
  3. do
  4.      echo "Student: $stud"
  5. done
Case Demo 2
  1. #!/bin/bash
  2. read -p "Please enter a number, the program will calculate the sum of all numbers from 1 to this number:" num
  3. s=0
  4. for ((i=1;i<=$num;i=i+1))
  5. do
  6.     s=$(($s+$i))
  7. done
  8. echo "The sum of all numbers from 1 to $num is: $s"

programming requirements

According to the requirements, supplement the code in the editor on the right, and use the for loop to print 5 lines of @ numbers that meet the requirements: the first line prints 1 @, the second line prints 2 @, the third line prints 3 @, and the fourth line prints line prints 4 @, and line 5 prints 5 @.

Test instruction

The platform will test the code you write:

Expected output:@ @@ @@@ @@@@ @@@@@

mission details

The task of this level: use the for loop to realize the value of the first 20 items of the Fibonacci sequence. 1 1 2 3 5 8 13 21  …

related information

In order to complete the task of this level, you need to master: the basic statement format of the for loop.

Case Demo 1

Suppose there are 4 students, namely Zhang San, Li Si, Wang Wu, and Zhao Liu. If each line is output in the style of "student:...", you can write the program as follows:

  1. #!/bin/bash
  2. for stud in Zhang San Li Si Wang Wu Zhao Liu
  3. do
  4.      echo "Student: $stud"
  5. done
Case Demo 2
  1. #!/bin/bash
  2. read -p "Please enter a number, the program will calculate the sum of all numbers from 1 to this number:" num
  3. s=0
  4. for ((i=1;i<=$num;i=i+1))
  5. do
  6.     s=$(($s+$i))
  7. done
  8. echo "The sum of all numbers from 1 to $num is: $s"

programming requirements

According to the requirements, supplement the code in the editor on the right, and use the for loop to realize the value of the first 20 items of the Fibonacci sequence. 1 1 2 3 5 8 13 21  …

Test instruction

The platform will test the code you write:

Expected output:1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

mission details

The task of this level: use the while statement to realize the output of numbers 1 to 10.

related information

In order to complete the task of this level, you need to master the basic format of the while statement.

Case Demo 1
  1. #!/bin/bash
  2. s=0
  3. i=0
  4. while [ "$i" != "100" ]
  5. do
  6.     i=$(($i+1))
  7.     s=$(($s+$i))
  8. done
  9. echo "The sum of all numbers from 1 to 100 is: $s"

programming requirements

According to the requirements, supplement the code in the editor on the right, and use the while statement to output the numbers 1 to 10.

Test instruction

The platform will test the code you write:

Expected output:1 2 3 4 5 6 7 8 9 10

mission details

The task of this level: use the until statement to realize the output of numbers 1 to 10.

related information

In order to complete the task of this level, you need to master the basic format of the :until statement.

Case Demo 1
  1. #!/bin/bash
  2. s=0
  3. i=0
  4. until [ "$i" = "100" ]
  5. do
  6.     i=$(($i+1))
  7.     s=$(($s+$i))
  8. done
  9. echo "The sum of all numbers from 1 to 100 is: $s"

programming requirements

According to the requirements, supplement the code in the editor on the right, and use the until statement to output the numbers 1 to 10.

Test instruction

The platform will test the code you write:

Expected output:1 2 3 4 5 6 7 8 9 10

Guess you like

Origin blog.csdn.net/qq_64314976/article/details/131413163