目录
1. if 语句
1.1 if - then-else 语句
if-then-else 用法如下:
if command
then
command
else
command
fi
1.2 if 语句嵌套
用法如下:
if command1
then
command1
elif command2
then
command2
elif command3
then
command3
else
command4
fi
2. test 语句
2.1 test 语句基本用法
用法如下:
if test condition
then
commands
fi
还有一种方法无需再语句中声明 test
,使用[]
符号,方法如下:
if [ condition ]
then
commands
fi
#这里方括号[]中间的条件语句两边必须加空格
2.2 数值比较
使用test
最常见的情形是对两个数值进行比较,下表为 test
数值比较表达式:
比较 | 描述 |
---|---|
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 |
2.3 字符串比较
test
也支持字符串比较,下表为字符串比较表达式:
比较 | 描述 |
---|---|
str1 = str2 | 两字符串相同 |
str1 != str2 | 两字符串不相同 |
str1 \< str2 | str1小于 str2,这里需加转义符,否则系统会将<当做重定向符号 |
str1 \> str2 | str1大于 str2,这里需加转义符,否则系统会将>当做重定向符号 |
-n str1 | str1 的长度不为 0 |
-z str1 | str1 的长度为 0 |
在测试比较中,大写字母被认为是小于小写字母的,这和sort
命令相反。
2.4 文件比较
shell 编程中常用到测试文件系统上文件及目录的状态,下面列出这些比较:
比较 | 描述 |
---|---|
-d file | 检查 file 是否存在且为目录 |
-f file | 检查 file 是否存在且为文件 |
-e file | 检查 file 是否存在 |
-r | 检查 file 是否存在且可读 |
-w | 检查 file 是否存在且可写 |
-x | 检查 file 是否存在且可执行 |
-s | 检查 file 是否存在且非空 |
-O file | 检查 file 是否存在且属于当前用户所有 |
-G file | 检查 file 是否存在且属于当前用户所在的组 |
file1 -nt file2 | 检查 file1 是否比 file2 新 |
file1 -nt file2 | 检查 file1 是否比 file2 旧 |
这里最后两个方法是用来对两个文件的创建时间进行比较。
2.5 复合条件测试
if
语句允许使用布尔逻辑组合进行测试,如下:
- [ condition1 ] && [ condition2 ]
- [ condition1 ] || [ condition2 ]
第一种使用的是 AND 布尔运算来组合两个条件,必须两个条件同时成立才为真。
第二种使用的是 OR 布尔运算来组合两个条件,两者只要有 一为真即真。
3. case 语句
case
命令会采用列表格式来检查单个变量的多个值,用法如下:
case variable in
pattern1 | pattern2)
command1;;
pattern3)
command2;;
*)
command3;;
esac
#这里每个命令结束要用两个分号;;隔开,最后的星号*表示与已知模式不匹配的值。
例:
#!/bin/sh
case $USER in
A | B)
echo "hello $USER"
echo "hello world";;
C)
echo "hello C";;
*)
echo "sorry, i do not know your name";;
esac