Shell condition judgment statement detailed analysis steps

Shell statement

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 (true true), it means success, and when the return value is non-zero (false false), it means failure or exception.

One, conditional statement

(1) test command

格式一:test 条件表达式
格式二:[ 条件表达式 ]

(2) File testing

格式:[ 操作符 文件或目录 ]
常用的操作符:
-e:测试目录或文件是否存在(Exist)。
-d:测试是否为目录(Directory)。
-f:测试是否为文件(File)。
-r:测试当前用户是否有权限读取(Read)。
-w:测试当前用户是否有权限写入(Write)。
-x:测试是否设置有可执行(Excute)权限。

Insert picture description here

(3) Integer value comparison

格式:[ 整数变量1 操作符 整数变量2 ]
常用的操作符:
-eq:等于					
-ne:不等于					
-gt:大于				
-lt:小于					
-le:小于等于
-ge:大于等于

Insert picture description here

(4) String comparison

格式1:
[  字符串1  =  字符串2 ] 或 [  字符串1  ==  字符串2 ] 
[  字符串1  !=  字符串2 ]

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

Insert picture description here

(5) Logic test

格式1:[  表达式1  ]  操作符  [  表达式2  ]  / [[ 表达式1 操作符 表达式2 ]]
格式2:命令1  操作符  命令2

常用的操作符:
-a或&& :逻辑与,“而且”的意思,前后条件需都成立
-o或|| :逻辑或,“或者”的意思,只需前后条件中一个成立
! :逻辑否

Insert picture description here

Two, if statement

(1) Single branch if statement

Insert picture description here

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

Insert picture description here

(2) Double branch if statement

Insert picture description here

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

example:

#!/bin/bash

read -p "输入性别" a
if [ $a = "男"  ]
then
        echo "$a 组"
else
        echo "女 组"
fi

Insert picture description here

(3) Multi-branch if statement

Insert picture description here

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

example:

#!/bin/bash
read -p "请输入您的分数(0-100): " z
if [ $z -ge 85 ] && [ $z -le 100 ]
then
        echo "$z 分,优秀!"
elif [ $z -ge 70 ] && [ $z -le 84 ]
then
        echo "$z 分,合格!"
else
        echo "$z 分,不合格!"
fi

Insert picture description here

Three, case statement

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

example:

#!/bin/bash
read -p "请输入您的分数(0-100): " w
[[ $w -ge 85 && $w -le 100 ]] && a="yx"
[[ $w -ge 70 && $w -lt 85 ]] && a="hg"
[[ $w -ge 0 && $w -lt 70 ]] && a="bhg"
case $a in
yx)
        echo " 优秀!"
;;
hg)
        echo "合格!"
;;
bhg)
        echo "不合格!"
;;
*)
        echo "输入有误!"
esac

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51468875/article/details/111314738