catalogue
(2) Syntax format of single branch if statement
(3) Structure diagram of single branch if statement
(2) Syntax format of double branch if statement
(3) Structure diagram of double branch if statement
(2) Syntax format of multi branch if statement
(3) Structure diagram of multi branch if statement
1. case multi branch structure
2. Syntax format of case multi branch statement
3. Structure diagram of case multi branch statement
introduction
When dealing with Linux system tasks, the script with a single sequential structure is often too slow and not intelligent. It is difficult to deal with more difficult system tasks, which brings a lot of workload to managers. From the reference to if statement and case statement, it can realize system tasks in batch, realize intelligence and improve the work efficiency of administrators.
1, Condition test
1. File test and integer test
(1) test command
Test whether the expression is true. If it is true, return 0; otherwise, return other values.
①Format 1: test Conditional expression ②Format 2:[ Conditional expression ]
(2) File test
① File testing refers to judging whether the corresponding file or directory is based on the given path name, or whether the file is readable, writable, executable, etc. The common operation options for file testing are as follows. When using, you can put the test object after the operation options.
[ Operator file or directory ]
② Common test operators
-d: Test whether it is a directory( Directory). -e: Test whether the directory or file exists( Exist). -f: Test whether it is a file( File). -r: Test whether the current user has permission to read( Read). -w: Test whether the current user has permission to write( write). -x: Test whether an executable is set( Excute)jurisdiction. -b: Test whether it is a device file. -c: Test whether it is a character device file. -s: The test exists and the file size is empty. -L: Test whether it is a linked file.
After the conditional test operation is executed, through the predefined variable $? The return status value of the test command can be obtained to judge whether the condition is true.
Do the following to test whether the directory / media / exists. If the return value is $? 0 indicates that this directory exists, otherwise it does not exist, or it exists but is not a directory.
[root@localhost ~]# Test - D / etc / sysconfig / & & echo "the test result is directory" The result of the test is the directory [root@localhost ~]# Test - F / etc / sysconfig / | echo "the test result does not match the file" The results of the test are not documented [root@localhost ~]# Test - E / etc / sysconfig / & & echo "the result of the test is the directory" The result of the test is the directory [root@localhost ~]# echo $? [root@localhost ~]# [ -d /home/admin/ ] [root@localhost ~]# echo $? 1 [root@localhost ~]# useradd admin [root@localhost ~]# [ -d /home/admin/ ] && echo "yes" yes [root@localhost ~]# echo $? 0 [root@localhost ~]# [ ! -e /opt/xm/ ] && mkdir /opt/xm/ [root@localhost ~]# echo $? 0 [root@localhost ~]# ls /opt/ rh xm
(3) Integer test
① Integer value comparison refers to judging the relationship between the first number and the second number according to the given two integer values, such as whether it is greater than, equal to or less than the second number. The common operation options for integer value comparison are as follows. When using, place the operation option between the two integers to be compared.
[ Integer 1 operator integer 2 ]
② Common test operators
-eq: The first number is equal to(Equal)The second number. -ne: The first number is not equal to( Not Equal)The second number. -gt: The first number is greater than(Greater Than)The second number. -lt: The first number is less than(Lesser Than)The second number. -le: The first number is less than or equal to(Lesser or Equal)The second number. -ge: The first number is greater than or equal to(Greater or Equal)Second number
[root@localhost ~]# [$(ll / usr | WC - L) - Le 15] & & echo "too few directories" Too few directories [root@localhost ~]# [$(ll / usr | WC - L) - Ge 10] & & echo "too many directories" too many directories [root@localhost ~]# Free1=$(free -m | grep "Mem:" | awk '{print $6}') [root@localhost ~]# [ $Free1 -lt 1024 ] && echo ${Free1}MB 459MB [root@localhost ~]# [ $Free1 -gt 300 ] && echo ${Free1}MB 459MB
2. String test and logic test
(1) String test
① String comparison is usually used to check whether the user input and system environment meet the conditions. In the Shell script that provides interactive operation, it can also be used to judge whether the location parameters entered by the user meet the requirements.
Format 1:[ String 1 = String 2 ];[ String 1 != String 2 ] Format 2:[ -z character string ]
② Common operation options for comparison are as follows.
-: The first string is the same as the second string. !=: The first string is different from the second string, where"!"The symbol indicates negation. -z: Check whether the string is empty( Zero),Variables that are not defined or assigned null values are treated as empty strings.
[root@localhost ~]# echo $LANG zh_CN.UTF-8 [root@localhost ~]# [ $LANG != "en.US" ] && echo "Not en.US" Not en.US [root@localhost ~]# read -p "overwrite existing file (yes/no)?" ACK Overwrite existing file( yes/no)?yes [root@localhost ~]# [$ack = "yes"] & & echo "overwrite" cover
(2) Logic test
① Logical testing refers to judging the dependency between two or more conditions. When the system task depends on several different conditions, a test process is required according to whether these conditions are true at the same time or as long as one of them is true.
Format 1:[ Expression 1 ] Operator [ Expression 2 ] ... Format 2: Command 1 operator command 2 ...
② Common logic test operations are as follows. When used, they are placed between different test statements or commands.
&&: Logic and, representation"and",The return value of the entire test command only when the last two conditions are true―Is 0 (the result is true). use test Command test“&&"Can be changed to"-a". ||: Logical or, representing"perhaps",As long as one of the two conditions is true, the return value of the whole test command is 0 (the result is true). use test Command test“||"Can be changed to"-o". !: Logical no means"no",The return value of the entire test command is 0 only when the specified condition is not true(The results are valid).
test etc Whether it is a directory and whether it has read permission. If both are, open it [root@localhost ~]# [ -d /etc ] && [ -r /etc ] && echo "You can open it" You can open it test etc Is it a directory or home Whether it is a directory. If one is established, click ok [root@localhost ~]# [ -d /etc ] || [ -d /home ] && echo "ok" ok
In the operation options of the above logic test, "& &" and "|" are usually used for command operations with different intervals, and their functions are similar. In fact, I have previously contacted the application of "& &" operation, such as the compilation and installation operation of "make & & make install". To determine whether the kernel version of the current Linux system is greater than 3.4, you can perform the following operations. The kernel version number is obtained by unane and awk commands.
2, if statement
1. if single branch statement
(1) Single branch structure
The "branch" of an if statement refers to the executed statements (one or more) corresponding to different test results. For the single branch selection structure, the corresponding code will be executed only when the condition is true, otherwise no operation will be performed.
(2) Syntax format of single branch if statement
if Conditional test operation then Command sequence fi
(3) Structure diagram of single branch if statement
[root@localhost ~]# vim test1.sh #!/bin/bash if ls /opt > /dev/null then echo "it's ok" fi [root@localhost ~]# sh test1.sh it's ok
[root@localhost ~]# vim test2.sh #!/bin/bash MOUNT_DIR="/mnt/centos7" if [ ! -d $MOUNT_DIR ] then mkdir -p $MOUNT_DIR echo "$MOUNT_DIR true" fi [root@localhost ~]# sh test2.sh /mnt/centos7 true
[root@localhost ~]# vim test3.sh #!/bin/bash read -p "Please enter a file name:" file if [[ $file==*.sh ]] then echo "This is shel script" fi [root@localhost ~]# sh test3.sh Please enter a file name: test1.sh This is shel script
2. if double branch statement
(1) Double branch structure
For the double branch selection structure, different operations are required for the two cases of "condition established" and "condition not established".
(2) Syntax format of double branch if statement
if Conditional test operation then Command sequence 1 else Command sequence 2 fi
(3) Structure diagram of double branch if statement
[root@localhost ~]# vim test4.sh #!/bin/bash IP=192.168.32.1 ping -c 5 -i 0.5 -w 7 $IP &> /dev/null if [ $? -eq 0 ] then echo "$IP is up" else echo "$IP is down" fi [root@localhost ~]# sh test4.sh 192.168.32.1 is up
[root@localhost ~]# vim test5.sh #!/bin/bash if [ $UID -eq 0 ] then echo "The currently logged in user is an administrator root" else echo "The currently logged in user is not an administrator root" fi [root@localhost ~]# sh test5.sh The currently logged in user is an administrator root
[root@localhost ~]# vim httpd1.sh #!/bin/bash netstat -anpt | grep 80 > /dev/null if [ $? = 0 ] then echo "The site service is already running" else echo "The web service has stopped running" echo "Please enter startup httpd Service command: systemctl start httpd" fi :wq [root@localhost ~]# sh httpd1.sh The web service has stopped running Please enter startup httpd Service command: systemctl start httpd [root@localhost ~]# systemctl start httpd [root@localhost ~]# sh httpd1.sh The site service is already running
3. if multi branch statement
(1) Multi branch structure
Because if statements can perform operations respectively according to whether the test results are true or not, they can be nested and used for multiple judgments.
(2) Syntax format of multi branch if statement
if Condition test operation 1 then Command sequence 1 elif Condition test operation 2 then Command sequence 2 else Command sequence 2 fi
(3) Structure diagram of multi branch if statement
[root@localhost ~]# vim test6.sh #!/bin/bash read -p "Please enter your score (0)-100): " GRADE if [[ $GRADE -le 100 && $GRADE -ge 85 ]] then echo "$GRADE Points: excellent!" elif [[ $GRADE -le 84 && $GRADE -ge 60 ]] then echo "$GRADE Score: qualified!" elif [[ $GRADE -le 59 && $GRADE -ge 0 ]] then echo "$GRADE Score: unqualified!" else echo "$GRADE : Invalid score, please re-enter!" fi [root@localhost ~]# sh test6.sh Please enter your score (0)-100): 50 50 Score: unqualified! [root@localhost ~]# sh test6.sh Please enter your score (0)-100): 70 70 Score: qualified! [root@localhost ~]# sh test6.sh Please enter your score (0)-100): 90 90 Points: excellent! [root@localhost ~]# sh test6.sh Please enter your score (0)-100): 110 110 : Invalid score, please re-enter!
[root@localhost ~]# vim fachao1.sh #!/bin/bash read -p "Please enter your test score (0)-100): " GRADE if [ $GRADE -eq 100 ] then echo "$GRADE Points: congratulations on getting full marks!" elif [[ $GRADE -le 99 && $GRADE -ge 90 ]] then echo "$GRADE Please copy the wrong questions 20 times!" elif [[ $GRADE -le 89 && $GRADE -ge 80 ]] then echo "$GRADE Please copy the wrong questions 20 times!" elif [[ $GRADE -le 79 && $GRADE -ge 60 ]] then echo "$GRADE Please copy the wrong questions 30 times!" elif [[ $GRADE -le 59 && $GRADE -ge 0 ]] then echo "$GRADE Please copy all the questions 30 times!" else echo "$GRADE : Invalid test score, please re-enter the test score!" fi :wq [root@localhost ~]# sh fachao1.sh Please enter your test score (0)-100): 115 115 : Invalid test score, please re-enter the test score! [root@localhost ~]# sh fachao1.sh Please enter your test score (0)-100): 100 100 Points: congratulations on getting full marks! [root@localhost ~]# sh fachao1.sh Please enter your test score (0)-100): 95 95 Please copy the wrong questions 20 times! [root@localhost ~]# sh fachao1.sh Please enter your test score (0)-100): 85 85 Please copy the wrong questions 20 times! [root@localhost ~]# sh fachao1.sh Please enter your test score (0)-100): 70 70 Please copy the wrong questions 30 times! [root@localhost ~]# sh fachao1.sh Please enter your test score (0)-100): 35 35 Please copy all the questions 30 times!
3, case statement
1. case multi branch structure
Case statements are mainly used in the following situations: a variable has multiple values, and different command sequences need to be executed for each value. This situation is very similar to multi branch if statements, except that if statements need to judge multiple different conditions, while case statements only judge different values of a variable.
2. Syntax format of case multi branch statement
case Variable value in Mode 1) Command sequence 1 ;; Mode 2) Command sequence 2 ;; ...... *) Default command sequence esac
3. Structure diagram of case multi branch statement
[root@localhost ~]# vim test7.sh #!/bin/bash case $1 in start) /usr/bin/systemctl $1 httpd echo "Opening httpd process" ;; stop) /usr/bin/systemctl $1 httpd echo "Stopping httpd process" ;; restart) /usr/bin/systemctl $1 httpd echo "Restarting httpd process" ;; status) /usr/bin/systemctl $1 httpd > /dev/null echo "Viewing httpd Process status: active (running)" ;; *) echo "Please enter a valid command: start or stop or restart or status" esac [root@localhost ~]# sh test7.sh st Please enter a valid command: start or stop or restart or status [root@localhost ~]# sh test7.sh stop Stopping httpd process [root@localhost ~]# sh test7.sh start Opening httpd process [root@localhost ~]# sh test7.sh restart Restarting httpd process [root@localhost ~]# sh test7.sh status Viewing httpd Process status: active (running)
[root@localhost ~]# vim fachao2.sh #!/bin/bash read -p "Please enter your test score (0)-100): " GRADE case $GRADE in 100) echo "$GRADE Points: congratulations on getting full marks!" ;; 9[0-9]) echo "$GRADE Points: please copy the wrong questions 10 times!" ;; 8[0-9]) echo "$GRADE Please copy the wrong questions 20 times!" ;; [6-7][0-9]) echo "$GRADE Please copy the wrong questions 30 times!" ;; [0-9]|[1-5][0-9]) echo "$GRADE Please copy all the questions 30 times!" ;; *) echo "$GRADE : Invalid test score, please re-enter the test score!" esac :wq [root@localhost ~]# sh fachao2.sh Please enter your test score (0)-100): 115 115 : Invalid test score, please re-enter the test score! [root@localhost ~]# sh fachao2.sh Please enter your test score (0)-100): 100 100 Points: congratulations on getting full marks! [root@localhost ~]# sh fachao2.sh Please enter your test score (0)-100): 95 95 Points: please copy the wrong questions 10 times! [root@localhost ~]# sh fachao2.sh Please enter your test score (0)-100): 85 85 Please copy the wrong questions 20 times! [root@localhost ~]# sh fachao2.sh Please enter your test score (0)-100): 65 65 Please copy the wrong questions 30 times! [root@localhost ~]# sh fachao2.sh Please enter your test score (0)-100): 45 45 Please copy all the questions 30 times! [root@localhost ~]# sh fachao2.sh Please enter your test score (0)-100): 7 7 Please copy all the questions 30 times!
summary
1. Use the [] or test command to perform conditional test operations, including file test, integer test, string test and logic test.
2. A status value will be returned after executing the command or program. If the return value is 0, it indicates that the execution is successful; If it is not 0, it indicates execution failure or exception.
3. By using if statements, you can selectively perform different operations according to conditions. The selection types include single branch, double branch and multi branch.
4. case statements can execute different command sequences according to different values of variables, which is clearer than multi branch if statements.