LinuxShell条件判断怎么写_ifcase语法详解
Linux Shell 中的条件判断主要靠 if 和 case 实现,写法简洁但细节关键——稍不注意就会因空格、引号或测试符号出错。
if 语句:基础结构与常见写法
if 用于基于命令执行结果(退出状态码)做逻辑分支。Shell 中命令成功返回 0,失败返回非 0,if 正是据此判断。
基本格式必须用 then 换行或跟分号:
if [ condition ]; then ... fi 或
if [ condition ]
then ...
fi
[ ] 是内置命令(等价于 test),左右方括号必须和条件之间有空格,例如 [ "$a" = "yes" ],写成 ["$a"="yes"] 会报“command not found”
字符串比较用 =(Bash 中也支持 ==,但 POSIX 兼容写法推荐 =);数值比较用 -eq、-lt 等,不能用 == 或
建议变量一律加双引号,避免空值或含空格时语法错误,如 [ "$USER" = "root" ]
if 判断常用条件示例
实际脚本中高频判断场景:
检查文件是否存在且为普通文件:[ -f "/path/to/file" ]
判断目录是否存在:[ -d "/tmp/logs" ]
判断字符串非空:[ -n "$INPUT" ] 或简写为 [ "$INPUT" ]
判断两个字符串相等:[ "$STATUS" = "active" ]
组合多个条件:用 &&(与)、||(或),注意优先级,必要时加括号,如 [ -f "$1" ] && [ -r "$1" ]
case 语句:匹配字符串模式的高效写法
case 更适合对单个变量做多值分发,比一长串 elif 更清晰、执行更快。
语法结构:
case $VAR in
pattern1) cmd1 ;;
pattern2|pattern3) cmd2 ;;
) default_cmd ;;
esac
每个 pattern 支持通配符: 匹配任意字符,? 匹配单字符,[abc] 匹配字符集
多个模式用 | 分隔,如 start|up) systemctl start app ;;
必须以 esac 结尾(case 倒写),不是 end 或 fi
匹配成功后自动跳出,无需 break;如需继续匹配后续分支,加 ; (Bash 4.0+)
易错点与调试技巧
新手常踩的坑,直接影响脚本健壮性:
[ ] 中的空格不可省:错误写法 [1 -eq 1](缺空格)会被当做一个命令名,报错
[[ ]] 是 Bash 扩展,支持正则 =~ 和更宽松的语法(如未引号变量有时不报错),但不兼容 POSIX shell(如 dash),生产脚本若需移植性,坚持用 [ ]
调试时加 set -x 可打印每条执行命令及其参数,快速定位条件为何没进分支
不确定条件结果?单独运行测试命令,比如输入 [ -f /etc/hosts ]; echo $? 查看退出码
http://omega.richardshwx.com/
http://bj-omega.richardshwx.com/
http://sh-omega.richardshwx.com/
http://szs-omega.richardshwx.com/
http://gz-omega.richardshwx.com/
http://cd-omega.richardshwx.com/
http://hz-omega.richardshwx.com/
http://sz-omega.richardshwx.com/
http://wh-omega.richardshwx.com/
http://cq-omega.richardshwx.com/
http://cs-omega.richardshwx.com/
http://nj-omega.richardshwx.com/
http://nb-omega.richardshwx.com/
http://tj-omega.richardshwx.com/
http://qd-omega.richardshwx.com/
http://wx-omega.richardshwx.com/

浙公网安备 33010602011771号