流程控制
if语法:
单分支结构
if 条件测试
then
命令
fi
双分支结构
if 条件测试
then
命令
else
命令
fi
多分支结构
if 条件测试1
then
命令1
elif 条件测试2
then
命令2
else
命令
fi
if 条件测试1
then
命令1
elif 条件测试2
then
命令2
elif 条件测试3
then
命令3
elif 条件测试4
then
命令4
else
命令
fi
if 条件测试;then
命令
else
命令
fi
if 条件测试1;then
命令1
elif 条件测试2;then
命令2
else
命令
fi
shell的条件测试
格式1:test 条件表达式
格式2:[ 条件表达式 ]
格式3:[[ 条件表达式 ]] 支持正则表达式 && ||
条件判断的组合: -a -o -n
&& 逻辑与
-a
条件表达式1 && 条件表达式2
条件表达式1 -a 条件表达式2
|| 逻辑或
-o
条件表达式1 || 条件表达式2
条件表达式1 -o 条件表达式2
! 非,取反
! 条件表达式
-n 条件表达式
文件测试
根据文件类型判断
-e 判断文件是存在
例:
[root@client tmp]# test -e /tmp
[root@client tmp]# echo $? 存在 状态返回值为0
0
[root@client tmp]# test -e /tmpdahs 不存在 状态返回值为1
[root@client tmp]# echo $?
1
-d 判断文件是存在且是为目录文件
-f 判断文件是存在且是为普通文件
-p 判断文件是存在且是为管道文件
-b 判断文件是存在且是为块设备文件
-c 判断文件是存在且是为字符设备文件
-L 判断文件是存在且是为软链接文件
-S 判断文件是存在且是为套接字文件
根据文件权限判断
-r 判断文件是存在且是有“可读权限”
-w 判断文件是存在且是有“可写权限”
-x 判断文件是存在且是有“可执行权限”
[root@client tmp]# test -r a.a.pdf 有读权限 状态返回值为0
[root@client tmp]# echo $?
0
[root@client tmp]# test -x a.a.pdf 无执行权限 状态返回值非0
[root@client tmp]# echo $?
1
文件内容非空白的判断
-s 判断文件是存在且文件内容非空白
[root@client tmp]# test -s /etc/passwd
[root@client tmp]# echo $? 非空,有内容 状态返回值为0
0
[root@client tmp]# test -s a.pdf 为空 状态返回值非0
[root@client tmp]# echo $?
1
数值比较
-gt 大于
-lt 小于
-eq 等于
-ge 大于等于
-le 小于等于
-ne 不等
[root@client tmp]# test 5 -gt 3 5大于3 结果为真 状态返回码为0
[root@client tmp]# echo $?
0
[root@client tmp]# test 3 -gt 3 3大于3 结果为假 状态返回码为非0
[root@client tmp]# echo $?
1
[root@client tmp]# A=5
[root@client tmp]# B=3
[root@client tmp]# test $A -gt $B
[root@client tmp]# echo $?
0
[root@client tmp]# test $B -gt $A
[root@client tmp]# echo $?
1
字符串比较 字符串一定要用引号引起来
== 等值比较
= 等值比较
[root@client tmp]# A=hello
[root@client tmp]# test $A == hello 结果为真 返回值0
[root@client tmp]# echo $?
0
[root@client tmp]# test $A == hell0 结果为假 返回值非0
[root@client tmp]# echo $?
1
!= 不等值比较
[root@client tmp]# A=hello
[root@client tmp]# test $A != hello 结果为假 返回值非0
[root@client tmp]# echo $?
1
[root@client tmp]# test $A != hell0 结果为真 返回值0
[root@client tmp]# echo $?
0
=~ 判断左侧字符串或者变量是否符合右侧的模式
-z 判断字符串是空
[root@client tmp]# unset A
[root@client tmp]# unset B
[root@client tmp]# A=8
[root@client tmp]# test -z $A 结果为假 返回值非0
[root@client tmp]# echo $?
1
[root@client tmp]# test -z $B 结果为真 返回值0
[root@client tmp]# echo $?
0