1.if-then语句
if command
then
commands
fi
如果command执行成功,exit 0的话 then条件成立,then 内的命令执行。
2.if-then-else 语句
if command
then
commands
else
commands
fi
当command执行成功的时候exit 0,执行then内语句,如果command执行不成功,exit非0的场合,执行else的内容。
3.嵌套if
if command1
then
commands_A
elif command2
then
commands_B
fi
command1的exit 0的场合,执行commands_A, command2的场合,执行commands_B,A,B只执行第一个。
4.判断命令test
test condition
用法:
if test condition
then
commands
fi
shell提供了一种简单方法[ ]
if [ condition ]
then
commands
fi
test命令可以进行三类条件比较
1.数值比较
2.字符串比较
3.文件比较
数值比较
n1 -eq n2 equal
n1 -ge n2 greater or equal
n1 -gt n2 greater than
n1 -le n2 less or euqal
n1 -lt n2 less than
n1 -ne n2 no equal
注意,只能处理整数
字符串比较
str1 = str2
str1 != str2
str1 < str2 大小写符号必须转移
str1 > str2 大小写符号和sort命令采取不同,大写字符小于小写字母
-n str1 非空
-z str1 空
文件比较
-d file directory判断是不是一个目录
-e file exist 判断文件是否存在
-f file file 判断文件是不是一个文件
-r file read 判断文件是否刻度
-s file 判断文件存在并且非空
-w file 判断文件可写
-x file 判断文件可执行
-0 file 判断文件属于当前用户
-G file 判断文件属于当前用户的组
file1 -nt file2 newer than file1比file2新
file1 -ot file2 older than file1比file2旧
符合测试条件
[ condition1 ] && [ condition2 ] AND
[ condition1 ] || [ condition2 ] OR
if-then 的高级特性
1)使用双圆括号
(( expression ))
运算符:
val++
val--
++val
--val
!
~
** 次幂
if (( $val1 ** 2 > 90 ))
2】使用方括号
[[ expression ]]
可以使用模式匹配,可以定义正则表达式来匹配字符串
case命令
case variable in
patteern1 | pattern2)
commands;;
pattern3)
commands2;
*)
default_commands;
esac
如果觉得《Linux学习 分支(if-then fi if then elif then fi case in );;easc》对你有帮助,请点赞、收藏,并留下你的观点哦!