Test conditions
Test file
integer test
string and logic test
The if statement
if a single branch statement
if dual branch statement
if a multi-branch statements
nested if statements
test command
Test specific expression is established when the condition is met, the test statement returns 0, otherwise other values
格式1: test 条件表达式
格式2:[ 条件表达式 ] //括号内空格
File test
[ 操作符 文件或目录 ] //括号内空格
Common test operators
-d: test whether the directory (Directory)
-e: test directory or file exists (Exist)
-f: Test whether the file (File)
-r: to test whether the current user has permission to read (Read )
-w: testing whether the current user has permission to write (the write)
-x: to test whether the current user has permission to perform (eXcute)
[root@localhost ~]# test -d /etc/sysconfig //判断是否为目录
[root@localhost ~]# echo $? //输出结果
0 //值为0时条件成立
[root@localhost ~]# test -f /etc/sysconfig //判断是否为文件
[root@localhost ~]# echo $?
1 //值为1时条件不成立
[root@localhost ~]# [ -e /etc/sysconfig ] //判断是否有权执行
[root@localhost ~]# echo $?
0
Integer value comparison
[ 整数1 操作符 整数2]
Common test operators
-eq: equal (Equal)
-ne: is not equal to (Not Equal)
-gt: greater than (the Greater Than)
-LT-: less than (Lesser Than)
-le: less than or equal to (Lesser or Equal)
-ge : equal to or greater than (Greater or equal)
[root@localhost ~]# [ $(who|wc -l) -le 6 ]&& echo "有点少!" //统计当前用户量
有点少!
String comparison
格式1: [ 字符串1 = 字符串2 ]
[ 字符串1 != 字符串2 ]
格式2: [ -z 字符串]
Common test operators
=: the same string content
=:! Different string content, expressed opposite meaning!
The -Z: the string is empty
Logic test
格式1: [ 表达式1 ] 操作符 [ 表达式2 ]
格式2: 命令1 操作符 命令2 ...
Common test operators
-a or &&: logical AND, "and" means
-o or ||: logical OR, "or" means
! : No logic
[root@localhost ~]# [ -x /etc ] || [ -w /etc ] &&echo "您可执行!" //满足一个条件即可
您可执行!
[root@localhost ~]# [ -x /etc ] && [ -w /etc ] &&echo "您可以操作!" //需同时满足两个条件
您可以操作!
The if statement
Single-branch structure
if //条件测试操作
then //命令序列
fi //结束命令序列判断
[root@localhost ~]# vim 111.sh
#!/bin/bash
read -p "请输入一个整数:" num
if [ $num -le 60 ]
then
echo "数字太小!"
fi
[root@localhost ~]# chmod +x 111.sh
[root@localhost ~]# ./111.sh
请输入一个整数:55
数字太小!
Two-branch structure
if //条件测试操作
then //命令序列1
else //命令序列2
fi //结束命令序列判断
[root@localhost ~]# vim 111.sh
#!/bin/bash
read -p "请输入一个整数:" num
if [ $num -le 60 ]
then
echo "数字太小!"
else
echo "数字太大!"
fi
[root@localhost ~]# ./111.sh
请输入一个整数:55
数字太小!
[root@localhost ~]# ./111.sh
请输入一个整数:88
数字太大!
Multi-branch structure
if //条件测试操作1
then //命令序列1
elif //条件测试操作2
then //命令序列2
else
//命令序列3
fi //结束命令序列判断
[root@localhost ~]# vim 111.sh
#!/bin/bash
read -p "请输入您的成绩:" num
if [ $num -le 10 ]
then
echo "恭喜您进入决赛!"
read -p "请输入您的性别(男/女):" sex
if [ $sex = "男" ]
then
echo "恭喜您进入男子组"
else
echo "恭喜您进入女子组"
fi
else
echo "很抱歉,您被淘汰了"
fi
[root@localhost ~]# ./111.sh
请输入您的成绩:8
恭喜您进入决赛!
请输入您的性别(男/女):男
恭喜您进入男子组
[root@localhost ~]# ./111.sh
请输入您的成绩:10
恭喜您进入决赛!
请输入您的性别(男/女):女
恭喜您进入女子组
[root@localhost ~]# ./111.sh
请输入您的成绩:20
很抱歉,您被淘汰了