9.1 使用if--then 语句
if command (如果命令的退出状态是0 。成功执行命令,则执行 then 后面所有的命令)
then
commands
fi
特别说明 ,grep hehehe /etc/passwd 如果没有匹配到值,则 $? 返回1
9.2 test 命令
如果 test 命令中列出的条件评估值为 true ,test 命令以0 退出状态代码退出
如果条件为 false ,则 test 命令退出 ,使 if--then 语句失效
语法
if test command
then
commands
fi
或者
if [ test ]
then
command
fi
test 命令主要用于 数字 ,字符串 ,文件 比较
9.2.1 比较数字
n1 -eq n2 n1==n2
n1 -ne n2 n1<>n2
n1 -ge n2 n1>=n2
n1 -gt n2 n1>n2
n1 -le n2 n1 <= n2
n1 -lt n2 n1< n2
9.2.2 字符串比较
str1 = str2
str1 != str2
str1 < str2
str1 > str2 (在使用中 > < 号需要转义,按标准的ascii 进行排序) ,与sort 排序不同
-z str 字符串长度是否为 0
-n str 字符串长度是否大于0
9.2.3 文件比较大小
-d file 检查file 是否存在并且是一个目录
-e file 检查file 是否存在
-f file 检查file是否存在,并且是一个文件
-r file 检查file 是否存在,并且可读
-w file 检查file 是否存在,并且可写
-s file 检查file 是否存在,并且不为空
-x file 检查file 是否存在,并且可执行
-O file 检查file是否存在 ,并且被当前用户拥有
-G file 检查file 是否存在,并且默认组是当前用户组
file1 -nt file2 检查file1 是否比file2新
file1 -ot file2 检查 file1 是否比 file2 旧
9.3 if -- then 高级特性
1.(( express )) express 可以是任何数学表达式 或 数学比较表达 式
2.[[ express ]] express 既可以 式 test 字符比较表达式,也可以是进行 模式匹配
如
if [[ $USER==r* ]]
then
echo "hello $USER"
else
echo "i don't know you"
fi
9.4 case
case 命令以 列表导向格式检查 单个变量的多个值
如
case variable in
pattern1 ) command1;;
pattern2 ) command2;;
*) default command;;
esac