* if-then的基本格式*
if command
then
commands
if
如果if条件为真,则执行then之后的语句
if command
then
echo 1
elif command2
then
echo 2
fi
类似java中的if-else if
if 后面可以判断三类条件:
一般情况都这样表示if[ ]注意第一个[ 和第二 ]必须有空格
1. 数值比较
2. 字符串比较
3. 文件比较
数值比较有两种
第一种简单举例:
n1 -eq n2 n1是否与n2相等
n1 -ge n2 n1是否大于等于n2
n1 -le n2 n1是否小于等于n2
#!/bin/bash
var1=$1
var2=3.14
if[ $var1 -gt 25 ]
then
echo "yes,you are right"
fi
第二种:用(( ))这种方式,可以使用高级数学表达式,val++
,val–,++val等等可直接写>,<,==,>==,记得里面的内容要与括号有空格
#!/bin/bash
if (( 2 >= 2 ))
then
echo 'you are the onwer of the /etc/passwd file'
else
echo 'Sorry,you are not the onwer of the /etc/passwd file'
fi
字符串比较较简单
常用的=,!=,<,>,-n(长度是否非0),-z(长度是否为0)
文件比较
-d file file是否存在并是一个目录
-f file file是否存在并是一个文件
-e file 检查file是否存在
**
if-then复合条件测试
[condition1] && [condition2]
[condition1] | | [condition2]
if-then高级特性
1.双方括号
[[ expression ]]注意要有空格,用于模式匹配
#!/bin/bash
if [[ $USER == r* ]]
then
echo "Welcome,$USER"
else
echo "hello,everybody"
fi
case命令
#!/bin/bash
case $USER in
root | hdfs)
echo "Welcome,$USER";;
*)
echo "hello,everybody";;
esac