第 12 章 结构化命令¶
约 237 个字 31 行代码 1 张图片 预计阅读时间 2 分钟
if/test/case 与数值、字符串、文件条件测试。
12.1 if-then / if-then-else¶
Bash
if command; then
commands
fi
if command; then
commands
else
commands
fi
if cmd1; then
...
elif cmd2; then
...
else
...
fi
注意:if 判断的是 退出状态码,非输出内容;if grep q /etc/passwd 找到则成功。
12.2 test / [ ]¶
数值比较(-eq -ne -gt -ge -lt -le)¶
字符串比较¶
| 运算符 | 含义 |
|---|---|
= / == |
相等 |
!= |
不等 |
< > |
字典序(需转义或 [[ ]]) |
-n str |
非空 |
-z str |
空 |
[[ ]](bash 扩展):支持 == 模式匹配、&& ||、无需转义 <。
算术比较 (( ))¶
文件测试¶
| 运算符 | 含义 |
|---|---|
-e |
存在 |
-f |
普通文件 |
-d |
目录 |
-r -w -x |
可读/写/执行 |
-s |
非空 |
-nt -ot |
比另一文件新/旧 |
-ef |
同一文件(硬链接) |