Conditional Statements of Shell Programming
1. Conditional test operation
1.test command
Test whether the expression is established, if not, return 0, otherwise return other values
格式1:test 条件表达式
格式2:[ 条件表达式 ]
2. File testing
[ 操作符 文件或目录 ]
Commonly used test operators
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) |
3. Integer value comparison
[ 整数1 操作数 整数2 ]
常用的测试操作符:
-eq #等于(Equal)
-ne #不等于(Not Equal)
-gt #大于(Greater Than)
-lt #小于(Lesser Than)
-le #小于或等于(Lesser or Equal)
-ge #大于或等于(Greater or Equal)
4. String comparison
格式1 [ 字符串1 = 字符串2 ]
[ 字符串1 != 字符串2 ]
格式2 [ -z 字符串 ]
=:第一个字符串与第二个字符串相同
!=:第一个字符与第二个字符串不相同,“!”表示取反
-z:字符串内容为空
-n:是否有字符串存在
5. Logic test
格式1:[ 表达式1 ] 操作符 [ 表达式2 ]
格式2:命令1 操作符 命令2
Commonly used operators:
-a或&& :逻辑与,“而且”的意思,前后条件需都成立
-o或|| :逻辑或,“或者”的意思,只需前后条件中一个成立
! :逻辑否
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
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 命令操作
Two, if statement
Single branch structure
格式:
if 条件测试操作
then
命令序列
fi
三种表达方式
方法一:
if [ 3 -gt 2 ]
then
echo "ok"
fi
方法二:
if [ 3 -gt 2 ]; then echo "ok"; fi
方法三:
[ 3 -gt 2 ] && echo "ok"
Double branch structure
格式:
if 条件测试操作
then
命令序列 1
else
命令序列 2
fi
Multi-branch structure
格式:
if 条件测试操作 1
then
命令序列 1
elif 条件测试操作 2
then
命令序列 2
[else]
[命令序列 3]
fi
Example: Prompt the user to enter the number of seconds for a 100-meter race, and ask to judge whether the number of seconds is greater than 0 and less than or equal to 10 seconds to enter the trial.
If the number of seconds is greater than 10 seconds, all will be eliminated. If other characters are entered , they will be prompted to re-enter; the members who enter the trial will be further judged Male and female gender, boys enter the boys group, girls enter the girls group, if you make a mistake, please indicate an error
Three, case branch statement
case 变量值 in
模式一)
命令序列
;;
模式二)
命令序列
;;
……
*)
默认命令序列
esac
Example: