Conditional statements of Shell programming Common conditional test operations, if conditional statements, case branch statements

1. Common condition test operations

1. File testing

The Shell environment judges whether the execution is successful according to the return status value ($?) after the command is executed. When the return value is 0, it means success, otherwise (non-zero value) means failure or exception. Use the special test tool-test command to test specific conditions and judge whether the condition is established according to the return value (the return value is 0 means the condition is established).

When using the test command, there are the following two forms.

test conditional expression
or
[conditional expression]

The effects of these two methods are exactly the same, but usually the latter form is more commonly used and closer to programming habits. It should be noted that at least one space is required between the square brackets "[" or "]" and the conditional expression.

File testing refers to judging whether the corresponding file or directory is based on a given path name, or judging whether the file is readable, writable, executable, etc. The common operation options of file testing are as follows. When using, put the test object after the operation options.

  • -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 the executable (Excute) permission is set.

After the conditional test operation is performed, the return status value of the test command can be obtained through the predefined variable $? to determine whether the condition is established.

For example, perform the following operations to test whether the directory /media/ exists, if the return value $? is 0, it means that the directory exists, otherwise it means it does not exist or although it exists, it is not a directory.

[root@localhost ~]# [ -d /root/media/ ]            //判断这个路径表示的是否为目录 
[root@localhost ~]# echo $?	                     //查看前一命令的返回值
0                                               //返回 0 表示条件成立  这是一个目录

If the condition of the test is not established, the return value of the test operation will not be 0 (usually 1). For example, performing the following operation shows the case where the test directory does not exist.

[root@localhost ~]# [ -d /media/cdrom/Server ]
[root@localhost ~]# echo $?	   //查看前一命令的返回值
1                             //返回 1 表示条件不成立

The conditional test result of the previous step can be judged by checking the value of the variable $?, but the operation is cumbersome and the output result is not very intuitive. In order to view the test results more intuitively, it can be used in conjunction with the command separator "&&" and the echo command, and directly output "YES" when the condition is established. Among them, the "&&" symbol indicates the relationship of "and", the following commands will be executed only after the current command is successfully executed, otherwise the following commands will be ignored. The above directory test operation can be rewritten as follows.

[root@localhost ~]# [ -d /media/cdrom/Server ] && echo "YES"	//无输出表示该目录不存在
[root@localhost ~]# [ -d /media/cdrom ] && echo "YES"	    //输出"YES"表示该目录存在
YES

2. Integer value comparison

Integer value comparison refers to judging the relationship between the first number and the second number based on two given 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, put the operation options between the two integers to be compared.

  • -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) the second number.

Integer value comparison is often used in shell scripting. For example, it is used to determine whether the number of logged-in users, the number of open processes, whether the disk usage exceeds the standard, and whether the software version number meets the requirements. In actual use, a value is often obtained through variable reference, command substitution, etc.

For example, if you want to judge the number of users currently logged in, and output "Too many." when it exceeds five, you can perform the following operations. Among them, the number of logged-in users can be obtained through the "who | wc -l" command, which is embedded in the form of command substitution.

[root@localhost ~]# Unum=`who | wc -l`	                 //查看当前已登录用户数
[root@localhost ~]# [ $Unum -gt 5 ] && echo "Too many." //测试结果(大于)
Too many.

To determine the current disk cache (buff/cache) size of the physical memory (Mem) and output the specific value when it is less than 1024MB, you can perform the following operations. Among them, the "free -m" command means to output memory information in MB, and the extracted free memory value is assigned to the variable FreeCC through command substitution.

[root@localhost ~]# FreeCC=$(free -m | grep "Mem: " | awk '{print $6}')
[root@localhost ~]# [ $FreeCC -lt 1024 ] && echo ${FreeCC}MB
275MB

3. String comparison

String comparison is usually used to check whether user input, system environment, etc. meet the conditions. In Shell scripts that provide interactive operations, it can also be used to determine whether the positional parameters input by the user meet the requirements. Common operation options for string comparison are as follows.

  • =: The first string is the same as the second string.
  • !=: The first character string is not the same as the second character string, and the "!" symbol indicates inversion.
  • -z: Check whether the string is empty (Zero). Variables that are not defined or assigned a null value will be regarded as empty strings.

For example, to determine the language environment of the current system and output the prompt message "Not en.US" when it is found that it is not "en.US", you can perform the following operations.

[root@localhost ~]# echo $LANG	//查看当前的语言环境
zh_CN.UTF-8
[root@localhost ~]# [ $LANG != "en.US" ] && echo "Not en.US" //字符串测试结果(不等于) 
Not en.US

In shell script applications, users are often required to enter "yes" or "no" to confirm a task. The following operations show the simple process of confirming the interaction. Of course, in actual use, further operations will be performed according to the value of the variable "ACK".

[root@localhost ~]# read -p "是否覆盖现有文件(yes/no)?" ACK
是否覆盖现有文件(yes/no)?yes
[root@localhost ~]# [ $ACK = "yes" ] && echo "覆盖"
覆盖
[root@localhost ~]# read -p "是否覆盖现有文件(yes/no)?" ACK
是否覆盖现有文件(yes/no)?no
[root@localhost ~]# [ $ACK = "no" ] && echo "不覆盖"
不覆盖

4. Logic test

Logic testing refers to judging the dependency between two or more conditions. When the system task depends on multiple different conditions, a testing process is required according to whether these conditions are established at the same time or as long as one of them is established. Commonly used logic test operations are as follows, and they are placed between different test statements or commands.

  • &&: Logical AND, which means "and", only when the last two conditions are both met, the return value of the entire test command is 0 (the result is true). When using the test command to test, "&&" can be changed to "-a".
  • ||: logical OR, which means "or", as long as one of the two conditions before and after is established, the return of the entire test command

The value is 0 (the result is true). When using the test command to test, "||" can be changed to "-o".

  • !: Logic N, means "No", only when the specified condition is not established, the return value of the entire test command is 0
    (the result is established).

For example, to determine whether the kernel version of the current Linux system is greater than 3.4, you can perform the following operations. Among them, the kernel version number is obtained through uname and awk commands.

[root@localhost ~]# uname -r	//查看内核版本信息3.10.0-514.el7.x86_64
[root@localhost ~]# Mnum=$(uname -r | awk -F. '{print $1}')	//取主版本号
[root@localhost ~]# Snum=$(uname -r | awk -F. '{print $2}')	//取次版本号
[root@localhost ~]# [ $Mnum -ge 3 ] && [ $Snum -gt 4 ] && echo "符合要求"
符合要求

Two, if conditional statement

In Shell script applications, the if statement is the most commonly used flow control method, used to perform different operations (if... then...) according to the test results of specific conditions. According to different levels of complexity, the selection structure of if statements can be divided into three basic types, which are suitable for different applications.

1. Single branch if statement

The "branch" of an if statement refers to the execution 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 met", otherwise no operation will be executed.

if conditional test operation
then
command sequence
fi
In the above statement structure, the conditional test operation can be either a "[conditional expression]" statement or other executable command statements; the command sequence refers to one or more executable The command line also includes nested if statements or other flow control statements.

The execution flow of a single-branch if statement: first judge the result of the conditional test operation, if the return value is 0, it means that the condition is satisfied, execute the command sequence after then, continue to execute other script codes until the judgment is completed when fi is encountered; if the return value If it is not 0, ignore the command sequence after then, jump directly to the fi line and execute other script codes.
Insert picture description here

2. Double branch if statement

For the dual-branch selection structure, different operations are required for the two cases of "conditions are established" and "conditions are not established".
If conditional test operations,
then
command sequence 1
else
command sequence 2
fi
double-branch if statement execution flow: first judge the conditional test As a result of the operation, if the condition is satisfied, execute the command sequence 1 after then, ignore the else and the following command sequence 2 until fi is met; if the condition is not satisfied, then ignore the then and the following command sequence 1, and jump directly to the else The following command sequence 2 is executed and executed until it meets fi and ends the judgment.
Insert picture description here

3. Multi-branch if statement

Since the if statement can perform operations according to whether the test result is true or not, it can be nested and used for multiple judgments.
if condition test operation 1
then
command sequence 1
elif condition test operation 2
then
command sequence 2
else
command sequence 3
fi

The execution flow of multi-branch if statement: first judge the result of conditional test operation 1, if condition 1 is established, execute command sequence 1, and then jump to fi to end the judgment; if condition 1 is not established, continue to judge the result of conditional test operation 2. If condition 2 is established, execute command sequence 2 and then jump to fi to end judgment... If all conditions are not met, execute command sequence n after else until it meets fi to end judgment.
Insert picture description here

Three, case branch statement

The case statement is mainly applicable to the following situations: a variable has multiple values, and a different sequence of commands needs to be executed for each value. This situation is very similar to the multi-branch if statement, except that the if statement needs to judge multiple different conditions, while the case statement only judges the different values ​​of a variable.

1. The format of the case statement

case variable value in
mode 1)
command sequence 1
;;
mode 2)
command sequence 2
;;
……
* )
default command sequence
esac

In the above statement structure, the keyword case is followed by "variable value", that is, "$variable name". The whole branch structure includes case...esac, the middle mode 1, mode 2, ... correspond to different values ​​of variables (the values ​​expected by the program), which can be used as wildcards to match any value.

The execution process of the case statement: first use the "variable value" to compare with mode 1, if the value is the same, execute the command sequence after mode 1 until it meets the double semicolon ";;" and then jump to esac, which means the end branch; If it does not match with mode 1, then continue to compare with mode 2, if the value is the same, execute the command sequence after mode 2 until it meets the double semicolon ";;" and then jump to esac, which means that the branch is ended. By analogy, if no matching value is found, the command sequence after the default pattern "*)" is executed until the branch is ended after esac is met
Insert picture description here

2. Points to note when using the case statement

Note : There are several noteworthy features when using case branch statements as described below.

  • The end of the case line must be the word "in", and each pattern must end with a closing bracket ")".
  • The double semicolon ";;" indicates the end of the command sequence.
  • In the pattern string, square brackets can be used to indicate a continuous range, such as "[0-9]"; the vertical bar symbol "|" can also be used to indicate or, such as "A|B".
  • The last " )" represents the default mode, which is equivalent to a wildcard.

Guess you like

Origin blog.csdn.net/wulimingde/article/details/108116554