Loop Statements and Functions in Shell Programming

Catalog 1. Looping statements 1. for Loop Statement (1) f...
1. for Loop Statement
2. while Loop Statement
3. until loop statement
1. Definition of functions
2. ShelI script debugging
1. Scenarios
2. Definition of arrays
3. Classification of Arrays
4. How arrays are defined

Catalog

1. Looping statements

1. for Loop Statement

(1) for statement

(2) Structure of statements

(3) Structural diagram of statements

2. while Loop Statement

(1) while statement

(2) Structure of statements

(3) Structural diagram of statements

3. until loop statement

(1) until statement

(2) Structure of statements

(3) Structural diagram of statements

2. Shell functions

1. Definition of functions

2. ShelI script debugging

3. Shell Arrays

1. Scenarios

2. Definition of arrays

3. Classification of Arrays

4. How arrays are defined

summary

In the use of circular statements and functions, and has a strong function, can easily complete more complex work, but also very good work efficiency, using operations personnel to more easily solve a series of complex problems, improve work efficiency.

1. Looping statements

1. for Loop Statement

(1) for statement

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

(2) Structure of statements

The action object of the for statement is a variable named by the user, and it is preset with a list of values separated by spaces through the in keyword. The sequence of commands located between do... done s is called a loop, in which the execution statement needs to reference the variable to complete the corresponding task.

for Variable Name in Value List do Command Sequence done

(3) Structural diagram of statements

for statement execution flow: first assign the first value in the list to a variable, and execute the command sequence in the do...do loop body; then assign the second value in the list to a variable, and execute the command sequence in the loop body... and so on until all values in the list are exhausted, and finally jump to the do statement to indicate the end of the loop.

inspect ping through ip Address Segment [root@localhost ~]# vim ip.sh #!/bin/bash for ((i=1;i<=255;i++)) do echo "192.168.32.$" >> /opt/ipadds.txt done HLIST=$(cat /opt/ipadds.txt) for IP in $HLIST do ping -c 1 -i 0.2 -w 1 $IP &> /dev/null if [ $? -eq 0 ];then echo "Host $IP is up" else echo "Host $IP is down" fi done :wq [root@localhost ~]# sh ip.sh Host 192.168.32.1 is up Host 192.168.32.2 is up Host 192.168.32.3 is down Host 192.168.32.4 is down Host 192.168.32.5 is down Host 192.168.32.6 is down Host 192.168.32.7 is down Host 192.168.32.8 is down Host 192.168.32.9 is down Host 192.168.32.10 is down Host 192.168.32.11 is down Host 192.168.32.12 is down Host 192.168.32.13 is down Host 192.168.32.14 is down Host 192.168.32.15 is down Host 192.168.32.16 is down Host 192.168.32.17 is down Host 192.168.32.18 is down Host 192.168.32.19 is down Host 192.168.32.20 is down
multiplication table [root@localhost ~]# vim jj1.sh #!/bin/bash for ((i=1;i<=9;i++)) do for ((j=1;j<=i;j++)) do echo -n "$i*$j=$((i*j)) " done echo "" done :wq [root@localhost ~]# sh jj1.sh 1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

2. while Loop Statement

(1) while statement

Repeatedly test a condition and execute it as long as the condition is valid

(2) Structure of statements

When using a while loop statement, a sequence of commands can be executed repeatedly based on specific conditions until the condition is no longer met. Dead loops should be avoided in scripting applications, otherwise command actions behind them will not be executed.Therefore, the command sequence within the loop should include statements that modify the test conditions so that at the appropriate time the test conditions are no longer valid and the loop ends.

while Conditional Test Operations do Command Sequence done

(3) Structural diagram of statements

The execution flow of the while statement: First judge the result of the conditional test operation after the while, and then execute do...done if the condition is valid.The sequence of commands in the loop body; judges the conditional test result again after returning while, and continues to execute if the condition still holds; judges the conditional test result after returning to while again... such a loop until the conditional test result after while no longer holds, and finally jumps to the do statement to end the loop.

[root@localhost ~]# vim WEBJK.sh #!/bin/bash DATE=`date +%Y-%m-%d-%T` while true do ps aux | grep httpd | grep -v grep &> /dev/null if [ $? -ne 0 ];then echo "httpd Service stopped running-$DATE!" >> /home/httpd.txt echo "httpd Service has stopped running, please handle the failure as soon as possible!" sleep 3 else echo "httpd Service is running!" sleep 3 fi done :wq [root@localhost ~]# sh WEBJK.sh httpd Service is running! httpd Service is running! httpd Service is running! httpd Service has stopped running, please handle the failure as soon as possible! httpd Service has stopped running, please handle the failure as soon as possible! httpd Service is running! httpd Service is running! httpd Service is running!
Guess commodity prices [root@localhost ~]# vim JG.sh #!/bin/bash PRICE=$(expr $RANDOM % 1000) a=0 echo "The actual price range of the commodity is 0-999,Guess what?" while true do read -p "Please enter the number of prices you guessed:" n let a++ if [ $n -eq $PRICE ] ; then echo "Congratulations on your correct answer. The actual price is $PRICE" echo "You guessed it all $a second" exit 0 elif [ $n -gt $PRICE ]; then echo "You guessed it!" else echo "You guessed it!" fi done :wq [root@localhost ~]# sh JG.sh The actual price range of the commodity is 0-999,Guess what? Please enter the number of prices you guessed: 850 You guessed it! Please enter the number of prices you guessed: 840 You guessed it! Please enter the number of prices you guessed: 830 You guessed it! Please enter the number of prices you guessed: 820 Congratulations, the actual price is 820 You guessed four times in total
Guess commodity prices [root@localhost ~]# vim JG1.sh #!/bin/ bash PRICE=`expr $RANDOM % 1000` a=0 echo "The actual price range of the commodity is 0-999,Guess what?" while true do read -p "Please enter the number of prices you guessed:" n let a++ if [ $n -eq $PRICE ] ; then echo "Congratulations on your correct answer. The actual price is $PRICE" echo "You guessed it all $a second" break elif [ $n -gt $PRICE ] ; then echo "You guessed it!" else echo "You guessed it!" fi done :wq [root@localhost ~]# sh JG1.sh The actual price range of the commodity is 0-999,Guess what? Please enter the number of prices you guessed: 300 You guessed it! Please enter the number of prices you guessed: 350 You guessed it! Please enter the number of prices you guessed: 310 You guessed it! Please enter the number of prices you guessed: 305 You guessed it! Please enter the number of prices you guessed: 308 Congratulations on your correct answer, the actual price is 308 You guessed 5 times in total

3. until loop statement

(1) until statement

Repeatedly test a condition and execute it as long as the condition is not established

(2) Structure of statements

The until loop is similar to the while loop, and the script until that the while loop can implement can also be implemented, but the difference is that the while loop continues when the condition is true, while until executes when the condition is false.

until Conditional Test Operations do Command Sequence done

(3) Structural diagram of statements

The execution flow of until statement: first judge the result of conditional test operation after until, if the condition is not established, execute the command sequence in the do...don loop body; second judge the result of conditional test after returning until, if the condition is still not established, continue to execute the loop body; after returning to until again, judge the result of conditional test...Until the test results are valid, jump to the do statement to end the loop.

1-50 Cumulative Sum [root@localhost ~]# vim JF1.sh #!/bin/bash i=1 sum=0 until [ $i -eq 51 ] do sum=$[$i+$sum] let i++ done echo "$sum" :wq [root@localhost ~]# sh JF1.sh 1275
2. Shell functions

1. Definition of functions

(1) Writing command sequences together in format makes it easy to reuse command sequences.

Functions are not automatically executed after they are defined, they need to be called. The advantage is that you can write a piece of function code as a function. If you need to call the definition directly, even if there are syntax errors, it will not make mistakes without calling. Of course, we write the function for the ultimate purpose or for calling, in order to achieve a function block.

[function] Function name() { Command Sequence [return x] }

(2) Function return value: return means exit function and returns an exit value, which can be used in scripts to show the principle of using the value with a $? Variable.
1. The return value is taken as soon as the function ends, because the $? Variable only returns the exit status code of the last command executed.
(2) Exit status code must be 0~255, exceeding time value will be divided by 256

(3) Methods of calling functions

Function name [Parameter 1] [Parameter 2]
install httpd service [root@localhost ~]# vim HTTPD1.sh #!/bin/bash set -x function backuprepo { cd /etc/yum.repos.d mkdir repo.bak mv *.repo repo.bak mount /dev/sr0 /mnt > /dev/null } makelocalrepo (){ echo -e ' [local] name=local baseurl=file:///mnt enabled=1 gpgcheck=0' > local.repo } uselocalrepo (){ yum clean all > /dev/null yum makecache > /dev/null yum install -y httpd> /dev/null systemctl start httpd } ##############main################## backuprepo makelocalrepo uselocalrepo :wq [root@localhost ~]# sh HTTPD1.sh + backuprepo + cd /etc/yum.repos.d + mkdir repo.bak + mv CentOS-Base.repo CentOS-CR.repo CentOS-Debuginfo.repo CentOS-fasttr ack.repo CentOS-Media.repo CentOS-Sources.repo CentOS-Vault.repo repo.bak+ mount /dev/sr0 /mnt mount: /dev/sr0 Write protected, mounted read-only + makelocalrepo + echo -e ' [local] name=local baseurl=file:///mnt enabled=1 gpgcheck=0' + uselocalrepo + yum clean all + yum makecache + yum install -y httpd + systemctl start httpd

2. ShelI script debugging

(1) echo command

(2) bash command: sh [-nvx] script name

-n: The script will not be executed, just query if there is a problem with the script syntax, if there are no syntax problems, nothing will be displayed, and if there are problems, an error will be prompted.
-v: When executing a script, first output the contents of the script to the screen and then execute the script. If there are any errors, an error prompt will be given.
-x: The output of the executed script to the screen is a useful parameter for debugging.

(3) set command
Set-x: turn on the adjustment mode;
set +x: Turn off the adjustment mode.

3. Shell Arrays

1. Scenarios

Get array length; Get element length; Traverse elements; Element slices; Element replacement; Element deletion

2. Definition of arrays

Arrays are collections of the same type of data that open up a continuous space in memory and are often used in conjunction with looping.

3. Classification of Arrays

Normal Array: There is no need to declare a direct definition; the subscript index can only be an integer.

Associated array: declare-A is required or the system does not recognize it, and the index can be a string.

4. How arrays are defined

Type (1): Enclose elements directly in parentheses, separated by spaces.

num=(11 22 33 44)

Type (2): Precisely define an array of values for each subscript index, and the index numbers can be discontinuous.

num=([0]=55 [1]=66 [2]=77 [4]=88)

Type (3): first assign all elements to an array to a variable, then add a reference to the variable to the array.

list="11 12 13 14" num=($list)

Type (4): The results of a command can be added to an array in parentheses, where each element is distinguished by a space or tab.

[root@localhost ~]# num=( `cat /etc/passwd` ) [root@localhost ~]# echo ${#num[*]} 92 [root@localhost ~]# echo $ root:x:0:0:root:/root:/bin/bash
[root@localhost ~]# an=(10 20 30 40 50) [root@localhost ~]# an_lg=$ [root@localhost ~]# echo $an_lg 10 20 30 40 50 [root@localhost ~]# an_lg=$ [root@localhost ~]# echo $an_lg 10 20 30 40 50 [root@localhost ~]# an_lg=${#an[@]} [root@localhost ~]# echo $an_lg 5 [root@localhost ~]# an_lg=$ [root@localhost ~]# echo $an_lg 30 [root@localhost ~]# arr=(1 2 3 4 5 6) [root@localhost ~]# for i in $ > do > echo $i > done 1 2 3 4 5 6 [root@localhost ~]# echo $ 4 5 6 [root@localhost ~]# echo $ 1 2 3 40 5 6 [root@localhost ~]# echo $ 1 2 3 4 5 6 [root@localhost ~]# unset arr[5] [root@localhost ~]# echo $ 1 2 3 4 5
summary

1. For statements can repeat command sequences based on known list objects, which is more suitable for irregular looping operations.
2. The while statement can repeat the command sequence according to specific conditions, which is more suitable for regular cyclic operation.
3. There are many service startup scripts on Linux system that define rich Shell functions and nest various statements.
4. Shell script debugging methods are echo command, bash command, set command.

13 September 2021, 23:21 | Views: 4346

Add new comment

For adding a comment, please log in
or create account

0 comments