Linux--Shell Programming--Conditional Statement


Preface

  • We have already learned to write a relatively simple shell script: each statement is executed in sequence, so as to realize the automatic process of "batch processing"
  • However, there are more "single" sequential structures written like this. Would you find it easier? In this way, the script is too mechanized, like a pipeline, not "smart" enough!
  • So, how can we calmly deal with complex system tasks?
  • Next, let’s learn how to perform conditional test operations, and through the correct use of if statements, so that the shell script has a certain "judgment" ability, so as to complete different management tasks according to different conditions

1. Condition test

1. Test command-test

  • To make the shell script program have a certain "smart", the first step is to distinguish between different situations to determine what operation to perform
  • The Shell environment judges whether the execution is successful according to the return status value ($?) after the command is executed . When it is 0, it is successful (indicating that the condition is established), otherwise (non-zero value) indicates failure or exception.
基本格式
test 条件表达式
[ 条件表达式 ]        ##此法更为常用,记住留有空格

2. File testing

基本格式:
[ 操作符 文件或目录 ]

echo &?
##0表示条件成立,反之亦然
可以结合&&使用,比if语句执行效率更高
  • Commonly used test operators ( back to me! fde, rwx )
Common operation options Explanation
-f Test whether it is a file (File)
-d Test whether it is a directory (Directory)
-e Test whether the directory or file exists (Exist)
-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 current user has permission to execute (Excute)
  • Examples are as follows
    mark
  • You can also use "[[]]" for conditional testing, where "||" is used
    mark
[root@localhost ~]# useradd xuer
[root@localhost ~]# echo "123123" | passwd --stdin xuer
更改用户 xuer 的密码 。
passwd:所有的身份验证令牌已经成功更新。
##新建一个用户用以测试用户权限
[root@localhost ~]# cd /
[root@localhost /]# touch xcf1.txt
[root@localhost /]# su - xuer
上一次登录:三 12月 16 14:31:40 CST 2020pts/1 上
[xuer@localhost ~]$ [ -r /xcf1.txt ] && echo "YES"
YES
[xuer@localhost ~]$ [ -w /xcf1.txt ] && echo "YES"

##可以看到这里新用户只具有读取但是没有写入的权限

3. Integer value comparison

基本格式:
[ 整数1 操作符 整数2 ]

##根据给定的两个整数值,判断前后关系,比如大、小,或等于
  • Give me back!
Common operators Explanation
-eq Equal
-born Not Equal
-gt Greater Than
-lt Less than (Lesser Than)
-give Greater or Equal
-the Less than or equal to (Lesser or Equal)
  • Example: Determine the size of the currently available free memory (free). If the current memory is less than 3333MB, it is recommended to clean it up in time (I have a higher configuration for the virtual machine here ==)
[root@localhost ~]# free -m        
              total        used        free      shared  buff/cache   available
Mem:           3774         278        3140           9         356        3237
Swap:          4093           0        4093

[root@localhost ~]# free -m | grep "Mem:" | awk '{print $4}'        
3140
[root@localhost ~]# abc=$(free -m | grep "Mem:" | awk '{print $4}')
[root@localhost ~]# echo $abc 
3139
[root@localhost ~]# [ $abc -lt 3333 ] && echo "当前内存为${abc}MB,请及时清理!"
当前内存为3139MB,请及时清理!

##查看当前内存大小
free 以kb单位显示  
free -m 显示MB  
free -h 仅centos7可用

4. String comparison

  • Usually used to check whether user input and system environment meet conditions
基本格式:
格式1
[ 字符串1 = 字符串2 ]
[ 字符串1 !=字符串2 ]
格式2
[ -z 字符串 ]
Commonly used test operators Explanation
= The first string has the same content as the second string
!= The first string is different from the second string! Sign means the opposite
-with Check whether the string content is empty. Variables that are not defined or assigned a null value will be treated as empty strings
[root@localhost ~]# read -p "思聪姓不姓王:(yes/no)" sicong
思聪姓不姓王:(yes/no)yes
[root@localhost ~]# [ $sicong = "yes" ] && echo "王思聪"
王思聪        ##若输出的是yes则输出王思聪,注意“=”两边的空格!
[root@localhost ~]# [ $sicong != "no" ] && echo "王思聪"
王思聪        ##若输入的不是no,则输出王思聪,注意“=”两边的空格!
[root@localhost ~]# [ -z $sicong ] && echo "王思聪"        ##检查是不是输入的是空格
[root@localhost ~]# 

5. Logic test

  • Determine the dependency between two or more conditions
  • When the system task depends on multiple different conditions, the judgment is based on whether these conditions are established at the same time or only one of them is established.
基本格式:
格式1:[ 表达式1 ] 操作符 [ 表达式2 ] ...
格式2:命令1 操作符 命令2 ...
  • Common test operators:
    • -a or &&: logical AND, meaning "and", both before and after conditions are met
    • -o or ||: logical OR, "or" meaning, one of the two is sufficient
    • ! : Logically no, only when the specified condition is not established, the result is established
  • "&&", "||" operators can normally exist in the "[[]]" conditional judgment structure, but if they appear in the "[]" structure, an error will be reported
[root@localhost ~]# a=5        ##为变量赋值
[root@localhost ~]# [ $a -ne 1 ] && [ $a -lt 8 ]        ##5大于1或5小于8
[root@localhost ~]# echo $?
0
[root@localhost ~]# [ $a -eq 1 ] && [ $a -lt 8 ]        ##5等于8?
[root@localhost ~]# echo $?
1        ##不成功
[root@localhost ~]# [ $a -ne 1 -a $a -lt 8 ]         ## -a的用法
[root@localhost ~]# echo $?
0
[root@localhost ~]# [[ $a -ne 1 && $a -lt 8 ]]        ## &&的用法
[root@localhost ~]# echo $?
0
[root@localhost ~]# [[ $a -ne 1 && $a -lt 8 ]] && echo abc123        ##不等于1且小于8就会输出abc123
abc123

Two, if statement

1. Single branch statement

mark

##基本格式
if 条件测试操作
    then  命令序列
fi
  • For example
[root@localhost ~]# vim aaa.sh

#!/bin/bash

xcf="xcf.txt"        ##这里可以先设变量

if [ ! -e $xcf ]        ##若文件不存在,则执行下述命令
 then
        touch $xcf
        echo "$xcf创建成功"
fi
[root@localhost ~]# chmod +x abc1.sh 
[root@localhost ~]# . aaa.sh 
xcf.txt创建成功

2. Double branch statement

mark

##基本格式
if 条件测试操作
	then  命令序列1
	else  命令序列2
fi
  • If the condition is true, execute the command after then, ignore the else, until the end of fi (here continue according to the previous template)
    mark
    mark
  • If the condition is not established, then ignore then, jump to the command sequence after else, until the end of fi
    mark
    mark

2.3 Multi-branch statement

mark

##基本格式
if 条件测试操作1
	then  命令序列1
elif  条件测试操作2
	then  命令序列2
else
	命令序列3
fi
[root@localhost ~]# vim ccc.sh

#!/bin/bash

read -p "请输入你的成绩(0~100):" cj

if [ $cj -ge 80 ] && [ $cj -le 100 ]
        then
                echo "优秀"

elif [ $cj -ge 60 ] && [ $cj -le 80 ]
        then
                echo "良好"

else
                echo "不及格"

fi

mark


Three, case branch statement

  • The case statement is mainly used in the following scenarios: when there are multiple values ​​for each variable, a different sequence of commands needs to be executed for each value
  • The if statement is to judge multiple different conditions, and case judges the different values ​​of a variable

1. Structure

mark

##基本格式
case 变量值 in
模式1)
	命令序列1
	;;
模式2)
	命令序列2
	;;
	....
*)
	默认命令序列
esac
  • The end of the case line must be the word in, and each line must end with a bracket ")"
  • The double semicolon ";;" indicates the end of the command sequence
  • You can use square brackets "[]" to indicate a continuous range; you can also use "|" to indicate, such as "A|B"
  • The last ")*" means the default mode, if the above values ​​are not the same, execute this line

2. Application examples

[root@localhost ~]# vim ddd.sh

#!/bin/bash
#不说了我要去罚抄了

read -p "请输入你的分数: " sub

case $sub in

100)
        echo "恭喜你 逃过一劫"
        ;;

8[0-9]|9[0-9])
        echo "每道错题抄10遍"
        ;;

6[0-9]|7[0-9])
        echo "每道错题抄20遍"
        ;;

*)
        echo "呵呵 全部30遍"

esac

[root@localhost ~]# chmod +x ddd.sh 
[root@localhost ~]# vim ddd.sh
[root@localhost ~]# . ddd.sh 
请输入你的分数: 100
恭喜你 逃过一劫
[root@localhost ~]# . ddd.sh 
请输入你的分数: 98
呵呵 全部30遍
[root@localhost ~]# vim ddd.sh
[root@localhost ~]# . ddd.sh 
请输入你的分数: 99
每道错题抄10遍
[root@localhost ~]# . ddd.sh 
请输入你的分数: 77
每道错题抄20遍
[root@localhost ~]# . ddd.sh 
请输入你的分数: 55
呵呵 全部30遍
[root@localhost ~]# . ddd.sh 
请输入你的分数: 100
恭喜你 逃过一劫

Guess you like

Origin blog.csdn.net/weixin_51486343/article/details/111300594