Shell programming conditional statement and case statement

A condition test

1.1 File testing

According to the given path name, determine whether it corresponds to a file or a directory. Or judge whether the file is readable, writable, and executable.
Common file operation options are as follows:

Operation options Explanation
-d (Directory) test whether it is a directory
-e (Exist) Test whether the directory or file exists
-f (File) test whether it is a file
-r (Read) Test whether the current user has permission to read
-w (Write) Test whether the current user has permission to write
-x (Excute) Test whether the executable permission is set

After executing the condition test operation, the return status value of the test command can be obtained through the predefined variable "$?". If the return value is 0, it means the condition is met; if the return value is not 0 (usually 1), it means the condition is not true.
Insert picture description here
Direct output
Insert picture description here
comparison between two files

Operation options Explanation
-nt Determine whether file A is newer than file B
-ot Determine whether file A is older than file B
-ef Determine whether two files are the same file, used to determine whether two files point to the same inode

Insert picture description here

1.2 Integer value comparison

Operation options Explanation
-eq The first integer is equal to the second integer
-born The first number is not equal to the second number
-gt The first number is greater than the second number
-lt The first number is lesser than the second number
-the The first number is less than or equal to the second number
-give The first number is greater or equal to the second number

Example:
Determine the number of currently logged-in users, output "too many" when more than 5, and the
Insert picture description here
extended
if statement can also be written in this form
Insert picture description here

1.3 String comparison

Operation options Explanation
= The first string is the same as the second string
!= The first string is different from the second
-with Check whether the string is empty (zero)

[String 1 = String 2]
[String 1 != String 2]
[-z String]
Insert picture description here
note
When there are spaces on both sides of the equal sign, double quotation marks need to be added to both the left and right sides. If the double quotation marks are not added to the left variable, the left and right sides of the equal sign do not need spaces.

Two if statement

2.1 Single branch structure of if statement

For the single-branch selection structure, the corresponding code will be executed only when the condition is satisfied, otherwise no operation will be executed. When only one situation needs to be determined, a single branch structure can be used.
Insert picture description here

if 条件测试操作 
then
	命令序列
fi

Example:

a=2
b=1
if [ $a -gt $b ]
then
	echo "$a$b大"
fi

It can also be written as a conditional test

[root@localhost ~]# [ $a -gt $b ] && echo "${a}bi${b}da"

Insert picture description here

2.2 Double branch structure of if statement

The dual-branch selection structure performs different operations for the two cases of "conditions are met" and "conditions are not met". When the decision result needs to be discussed in two situations, a dual-branch structure is generally adopted.
Insert picture description here

if 条件测试操作 
then
	命令序列1
else
	命令序列2
fi

Example:

#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null	//表示ping3次,每次间隔0.2秒,等待超时3秒;$1表示第一个位置参数
if [ $? -eq 0 ]		//判断前一条命令的返回状态
then
	echo "Host $1 is up."
else
	echo "Host $1 is down."
fi

Written as a conditional test

[root@localhost ~]# [ $? -eq 0 ] && echo "up" || echo "down"

Insert picture description here

2.3 Multi-branch structure of if statement

The multi-branch selection structure performs different operations for various situations. The multi-branch structure can be used when the decision result needs to be discussed in three or more situations.
Insert picture description here

if 条件测试操作1 
then
	命令序列1
elif 条件测试操作2
then
	命令序列2
else
	命令序列3
fi

Example:

#!/bin/bash
read -p "请输入你想考的分数:" GRADE
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ]
then
        echo "$GRADE 分,优秀"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ]
then
        echo "$GRADE 分,合格"
else
        echo "$GRADE 分,不及格"
fi

Conditional statement

[root@localhost ~]# [ $GRADE -ge 85 ] && [ $GRADE -le 100 ] && echo "$GRADE 分,优秀" || [ $GRADE -ge 70 ] && [ $GRADE -le 84 ] && echo "$GRADE 分,合格" || echo "$GRADE 分,不及格"

Insert picture description here

2.4 The magical effect of $0

The robustness of the above program still needs to be improved, because when inputting other abnormal scores, it will display "unqualified" by default. At this time, you can use $0 to return to the current program and force the user to enter a normal score, such as a score between 0-100 .

if语句判断成绩
#!/bin/bash
read -p "请输入您的分数(0-100):" GRADE
cj(){
    
    
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ]
then
        echo "$GRADE 分,优秀"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ]
then
        echo "$GRADE 分,合格"
else
        echo "$GRADE 分,不及格"
fi
}

if [ $GRADE -gt 100 ] | [ $GRADE -lt 0 ]
then
        echo "please input right number"
        $0
else
        cj
fi

Three case statements

Multi-branch if statements can be rewritten with case statements, so that the operation can make the structure clearer and clearer
Insert picture description here

case 变量值 in
模式1)
	命令序列1
	;;
模式2)
	命令序列2
	;;
	......
	
*)
	默认命令序列
esac

Example 1:
Judging the ranking of results, because the case statement cannot match the range (except for [0-9], [az], [AZ]), here you can write a function judge() to classify all the numbers in a range into One type, return the same value, and then use the case statement to classify and judge the value.
method 1:

#!/bin/bash
read -p "请输入你想考的分数:" GRADE
judge(){
    
    
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ]
then
        echo "a"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ]
then
        echo "b"
fi						//else可省略
}

case `judge` in			//调用函数judge()
a)
        echo "$GRADE 分,优秀"
        ;;
b)
        echo "$GRADE 分,合格"
        ;;
*)
        echo "$GRADE 分,不及格"
esac

Method 2

#!/bin/bash
read -p "请输入你的成绩:" GRADE
case "$GRADE" in
#[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])
[1-5][0-9]|[0-9])
        echo "你的成绩不合格"
        ;;
6[0-9]|7[0-4])
        echo "你的成绩合格"
        ;;
7[5-9]|8[0-4])
        echo "你的成绩良好"
        ;;
8[5-9]|9[0-9]|100)
        echo "你的成绩优秀"
        ;;
*)
        echo "输入有误"
esac

Example 2:
Use a shell script to implement the http switch operation.
Insert picture description here
Awk represents the extraction field, which will be explained in detail in the following blog

Guess you like

Origin blog.csdn.net/cenjeal/article/details/107970330