一、使用if-then语句
格式:
if comand
then
commands
fi
或者下种格式:
if command;then
commands
fi
检查command命令执行成功($?),则执行then后面的指令
二、使用if-then-else语句
格式:
if command
then
commands
else
commands
fi
或者下述格式
if comand;then
commands
else
commands
fi
如果command执行成功,则执行then后面的语句,否则执行else后面的语句
三、嵌套if
格式如下
if command1
then
commands
elif command2
then
commands
elif command3
then
commands
fi
四、test命令
上述if后面的条件都是和命令行执行结果相关的,下述的判断条件与命令行执行无关。
格式
if test condition
then
commands
fi
或下面格式
if [ condition ]
then
commands
fi
condition可以判断三种条件:
1、数据比较
2、字符串比较
3、文件比较
4.1 数据比较
比 较 | 描 述 |
n1 -eq n2 | 检查n1 n2是相等 |
n1 -ge n2 | 检查n1是否大于等n2 |
n1 -gt n2 | 检查n1是否大于n2 |
n1 -le n2 | 检查n1是否小于等于n2 |
n1 -lt n2 | 检查n1是否小于n2 |
n1 -ne n2 | 检查n1 是否不等于n2 |
example:
var1=1
var2=2
if [ $var1 -eq $var2 ];then
echo var1 is not equal to var2
fi
4.2 字符串比较
比 较 | 描述 |
str1 = str2 | 检查字符串str1和str2是否相同 |
str1 != str2 | 检查字符串str1和str2是否不相同 |
str1 < str2 | 检查字符串str1是否比str2小 |
str1 > str2 | 检查字符串str1是否比str2大 |
-n str1 | 检查字符串str1是否为非空 |
-z str1 | 检查字符串str1是否为空 |
example:
str1=hello
str2=world
if [ $str1 = $str2 ];then
echo str1 is not equal to str2
fi
str1=''
if [ -n $str1 ];then
echo str1 is not empty
fi
4.3 文件比较
比较 | 描述 |
-d file | 检查file是否存在并且是目录 |
-e file | 检查file是否存在 |
-f file | 检查file是否存在并且是个文件 |
-r fle | 检查file是否存在并可读 |
-w file | 检查文件file是否存在并可写 |
-x file | 检查文件file是否存在并可执行 |
-s file | 检查文件是否存在并且非空 |
-O file | 检查文件file是否存在并归当前用户所有 |
-G file | 检查file是否存在并且默认组与当前用户相同 |
file1 -nt file2 | 检查file1是否比file2新 |
file1 -ot file2 | 检查file1是否比file2旧 |
五、复合测试条件
六、if-then高级特性
6.1 使用双圆括号
(( expression ))
6.2 使用双方括号
[[ expression ]]
支持正则表达式里的模式匹配
example:
if [[ $USER == r* ]]
then
echo $USER
else
echo "sorry to konw"
fi
七、case命令
case命令格式如下:
case variable in
pattern1 | pattern2)
commands;;
pattern3) commands;;
*) commands;;
esac