Secretly learn the conditional statements of shell scripts

1. Conditional test operation

1. Test command------test

  • You can test specific conditions and determine whether the condition is established based on the return value (the return value is 0 means the condition is established, otherwise it is not).
使用test命令测试时,有两种形式:(常用格式二)
格式一:test 条件表达式
格式二:[ 条件表达式 ]
#方括号两边与条件表达式之间需要至少一个空格进行分隔

2. File testing

  • According to the given path name, determine whether it corresponds to a file or a directory, or whether it has the corresponding authority.
格式:[ 操作符 文件或目录 ]
Commonly used operators effect
-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 current user has permission to execute (Excute)

Insert picture description here

3. Integer value comparison

  • Used to compare the size of two integer values.
格式:[ 整数变量1 操作符 整数变量2 ]
Commonly used operators effect symbol
-eq equal ==
-born not equal to !=
-gt more than the >
-lt Less than <
-the Less than or equal to
-give greater or equal to

Example 1:

ps aux |wc -l
[ $(ps aux| wc -l) -lt 200 ] && echo "系统进程状况良好" || echo "后台程序太多,请及时清理"

Insert picture description here
Example 2:

Free=$(free -m | grep "Mem" | awk '{print $4}')
[ $Free -lt 1024 ] && echo "空闲内存所剩不多,只剩下${Free}MB"

Insert picture description here

4. String comparison

  • String can be used to check whether user input, system environment, etc. meet the conditions
  • In interactive shell scripts, used to determine whether the positional parameters input by the user meet the requirements
Common options effect
= The first string is the same as the second string
!= The first character is not the same as the second string, "!" means negation
-with The string content is empty
格式1:
[  字符串1  =  字符串2 ][  字符串1  ==  字符串2 ] 
[  字符串1  !=  字符串2 ]

格式2:
[  -z  字符串 ]		#检查字符串是否为空(Zero),对于未定义或赋予空值的变量将视为空串

Insert picture description here

5. Logic test

  • Used to judge the dependency between two or more conditions
常用的操作符:
-a或&& :逻辑与,“而且”的意思,前后条件需都成立
-o或|| :逻辑或,“或者”的意思,只需前后条件中一个成立
! :逻辑否,“不”的意思

格式1:[  表达式1  ]  操作符  [  表达式2  ]  
格式2:命令1  操作符  命令2
示例:
a=5
[ $a -ne 1 ] && [ $a != 2 ]	等同于	[ $a -ne 1 -a $a != 2 ]

#、&&、||操作符能够正常存在于[[ ]]条件判断结构中,但是如果出现在[ ]结构中的话,会报错
[[ $a -ne 1 && $a != 2 ]]
[ 2 -lt 3 ] && echo true || echo false
[ 2 -ge 3 ] && echo true || echo false

Insert picture description here
Insert picture description here

小实验:
vim pinghost.sh
#!/bin/bash
ping -c 3 -i 0.5 -W 2 $1 &> /dev/null && echo "$1 online" || echo "$1 off"

-c:发送包的个数
-i:发送包的间隔时间
-W:超时时间
-w:多少秒后停止 ping 命令操作

Insert picture description here

Two, if statement

1. Single branch structure

  • The corresponding operation will be executed only when the condition is established, otherwise it will not be executed.
格式:
if 条件测试操作
then
命令序列
fi

Insert picture description here

演示1:正常的if语句格式,看起来整洁,一目了然,如果报错提示行数容易发现。(推荐使用)
if [ 3 -gt 2 ]
 then
 echo "ok"
fi

演示2:都集中在一行,用“;”隔开,报错不易发现。(如果你认为自己不会出错,可以试试)
if [ 3 -gt 2 ]; then echo "ok"; fi

演示3:由条件测试拼凑而。(同2)
[ 3 -gt 2 ] && echo "ok"

Insert picture description here

2. Double branch if statement

  • Perform different operations for the two situations
格式:
if 条件测试操作
then
命令序列 1
else
命令序列 2
fi

Insert picture description here

这里就拿刚才上面逻辑测试里确定做成一个
vim pinghost.sh
#!/bin/bash
ping -c 3 -i 0.5 -W 2 $1 &> /dev/null
if [ $? -eq 0 ]
then
	echo "$1 online"
else
	echo "$1 off"
fi

Insert picture description here
Insert picture description here

3. Multi-branch if statement

  • According to the characteristics of if, it is used in nesting, and multiple judgments are made.
格式:
if 条件测试操作 1
then
命令序列 1
elif 条件测试操作 2
then
命令序列 2
[else]
[命令序列 3]
fi

Insert picture description here

vim dan.sh
#!/bin/bash
#
read -p "请输入您的积分: " score
if [ $score -ge 6000 ]
then
  echo "您在本店是至尊VIP!买东西享5折优惠!" 

  elif [ $score -ge 4000 ] && [ $score -le 5999 ]
  then
    echo "您在本店是顶级VIP!买东西享7折优惠!"

  elif [ $score -ge 2000 ] && [ $score -le 3999 ]
  then
    echo "您在本店为高级VIP!买东西享8折优惠!"

  elif [ $score -ge 1 ] && [ $score -le 1999 ]
  then
    echo "您在本店为普通VIP,买东西享9.5折优惠"

  elif [ $score -eq 0 ]
  then
    echo "您还未在本店购买过东西,没有任何优惠"
fi

Insert picture description here
Insert picture description here

Three, case branch statement

1. The structure of the case statement

  • Used for variables with multiple values, execute different commands for each value
  • Similar to if,
case 变量值 in
模式 1)
命令序列 1
;;
模式 2)
命令序列 2
;;
* )
默认命令序列
esac

When using case branch statements, there are several noteworthy features 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]", and the vertical bar symbol "|" can also be used to indicate or, such as "A|B".
  • The last "*)" represents the default mode, and the * is equivalent to a wildcard.
    Insert picture description here

2. Application examples

(1) Enter the score and confirm the evaluation

vim score.sh
#!/bin/bash
#
read -p "请输入您的分数(0-100): " score
[[ $score -ge 85 && $score -le 100 ]] && a="great"
[[ $score -ge 60 && $score -lt 85 ]] && a="standard"
[[ $score -ge 0 && $score -lt 60 ]] && a="false"
case $a in
great)
        echo "$score 分,优秀!"
;;
standard)
        echo "$score 分,合格!"
;;
false)
        echo "$score 分,不合格!"
;;
*)
        echo "输入有误!"
esac

Insert picture description here
Insert picture description here

(2) Writing system service scripts

vim /etc/init.d/firewalld.sh
#!/bin/bash
#
case $1 in
start)
        echo "正在开启防火墙..."
        systemctl start firewalld.service
  if [ $? -eq 0 ]
  then
  echo "开启成功"
  else
  echo "开启失败"
  fi
;;
stop)
        echo "正在关闭防火墙..."
        systemctl stop firewalld.service
  if [ $? -eq 0 ]
  then
  echo "已关闭"
  else
  echo "关闭失败"
  fi
;;
restart)
        $0 stop
        $0 start
;;
status)
  echo "防火墙状态如下:"
        systemctl status firewalld.service
;;
* )
        echo "脚本的用法: $0 {start|stop|status|restart}"
esac

Experimental script:
Insert picture description here
Test script:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51326240/article/details/111294850