条件判断if #

一、if语句基础 #

1.1 基本语法 #

bash
# 基本if语句
if [ condition ]; then
    # 条件为真时执行
fi

# if-else语句
if [ condition ]; then
    # 条件为真时执行
else
    # 条件为假时执行
fi

# if-elif-else语句
if [ condition1 ]; then
    # 条件1为真时执行
elif [ condition2 ]; then
    # 条件2为真时执行
else
    # 所有条件都为假时执行
fi

1.2 简单示例 #

bash
#!/bin/bash

age=18

# 基本if语句
if [ $age -ge 18 ]; then
    echo "已成年"
fi

# if-else语句
score=75
if [ $score -ge 60 ]; then
    echo "及格"
else
    echo "不及格"
fi

# if-elif-else语句
grade=85
if [ $grade -ge 90 ]; then
    echo "优秀"
elif [ $grade -ge 80 ]; then
    echo "良好"
elif [ $grade -ge 70 ]; then
    echo "中等"
elif [ $grade -ge 60 ]; then
    echo "及格"
else
    echo "不及格"
fi

二、条件表达式 #

2.1 使用test命令 #

bash
#!/bin/bash

# 使用 [ ] (等同于test)
if [ -f /etc/passwd ]; then
    echo "文件存在"
fi

# 使用 [[ ]] (Bash增强版,推荐)
if [[ -f /etc/passwd ]]; then
    echo "文件存在"
fi

# 使用 (( )) (算术比较)
a=10
if (( a > 5 )); then
    echo "a大于5"
fi

2.2 文件测试 #

bash
#!/bin/bash

file="/etc/passwd"

# 文件存在
if [ -e "$file" ]; then
    echo "文件存在"
fi

# 是普通文件
if [ -f "$file" ]; then
    echo "是普通文件"
fi

# 是目录
if [ -d "/etc" ]; then
    echo "/etc 是目录"
fi

# 可读
if [ -r "$file" ]; then
    echo "文件可读"
fi

# 可写
if [ -w "$file" ]; then
    echo "文件可写"
fi

# 可执行
if [ -x "$file" ]; then
    echo "文件可执行"
fi

2.3 字符串测试 #

bash
#!/bin/bash

str="hello"

# 字符串非空
if [ -n "$str" ]; then
    echo "字符串非空"
fi

# 字符串为空
if [ -z "$str" ]; then
    echo "字符串为空"
fi

# 字符串相等
if [ "$str" = "hello" ]; then
    echo "字符串等于hello"
fi

# 字符串不相等
if [ "$str" != "world" ]; then
    echo "字符串不等于world"
fi

2.4 数值比较 #

bash
#!/bin/bash

a=10
b=5

# 使用 -eq, -ne, -gt, -ge, -lt, -le
if [ $a -gt $b ]; then
    echo "$a 大于 $b"
fi

# 使用 (( ))
if (( a > b )); then
    echo "$a 大于 $b"
fi

# 复杂比较
if (( a >= 10 && a <= 20 )); then
    echo "$a 在10到20之间"
fi

三、组合条件 #

3.1 逻辑与 #

bash
#!/bin/bash

age=25
has_license=true

# 使用 && 连接
if [ $age -ge 18 ] && [ "$has_license" = true ]; then
    echo "可以驾驶"
fi

# 在 [[ ]] 中使用 &&
if [[ $age -ge 18 && $has_license == true ]]; then
    echo "可以驾驶"
fi

# 使用 -a
if [ $age -ge 18 -a "$has_license" = true ]; then
    echo "可以驾驶"
fi

3.2 逻辑或 #

bash
#!/bin/bash

day="Saturday"

# 使用 || 连接
if [ "$day" = "Saturday" ] || [ "$day" = "Sunday" ]; then
    echo "周末"
fi

# 在 [[ ]] 中使用 ||
if [[ $day == "Saturday" || $day == "Sunday" ]]; then
    echo "周末"
fi

# 使用 -o
if [ "$day" = "Saturday" -o "$day" = "Sunday" ]; then
    echo "周末"
fi

3.3 逻辑非 #

bash
#!/bin/bash

file="/tmp/nonexistent"

# 使用 !
if [ ! -f "$file" ]; then
    echo "文件不存在"
fi

# 在 [[ ]] 中使用 !
if [[ ! -f "$file" ]]; then
    echo "文件不存在"
fi

# 复杂条件
if [[ ! ($a -gt 10 && $b -gt 10) ]]; then
    echo "a或b不都大于10"
fi

四、嵌套if语句 #

4.1 基本嵌套 #

bash
#!/bin/bash

age=25
has_license=true

if [ $age -ge 18 ]; then
    echo "年龄符合要求"
    
    if [ "$has_license" = true ]; then
        echo "有驾照,可以驾驶"
    else
        echo "没有驾照,不能驾驶"
    fi
else
    echo "年龄不符合要求"
fi

4.2 使用elif替代嵌套 #

bash
#!/bin/bash

# 不推荐:深层嵌套
score=85
if [ $score -ge 90 ]; then
    echo "优秀"
else
    if [ $score -ge 80 ]; then
        echo "良好"
    else
        if [ $score -ge 70 ]; then
            echo "中等"
        else
            if [ $score -ge 60 ]; then
                echo "及格"
            else
                echo "不及格"
            fi
        fi
    fi
fi

# 推荐:使用elif
if [ $score -ge 90 ]; then
    echo "优秀"
elif [ $score -ge 80 ]; then
    echo "良好"
elif [ $score -ge 70 ]; then
    echo "中等"
elif [ $score -ge 60 ]; then
    echo "及格"
else
    echo "不及格"
fi

五、if语句高级用法 #

5.1 命令执行结果作为条件 #

bash
#!/bin/bash

# 检查命令是否成功
if ping -c 1 google.com &>/dev/null; then
    echo "网络正常"
else
    echo "网络异常"
fi

# 检查进程是否存在
if pgrep nginx &>/dev/null; then
    echo "nginx正在运行"
else
    echo "nginx未运行"
fi

# 检查命令是否存在
if command -v git &>/dev/null; then
    echo "git已安装"
else
    echo "git未安装"
fi

5.2 使用grep匹配 #

bash
#!/bin/bash

file="config.txt"

# 检查文件是否包含某行
if grep -q "ERROR" "$file"; then
    echo "发现错误日志"
fi

# 使用正则表达式
if grep -qE "^[0-9]+$" <<< "$input"; then
    echo "输入是数字"
fi

5.3 使用管道和条件 #

bash
#!/bin/bash

# 检查服务状态
if systemctl is-active --quiet nginx; then
    echo "nginx服务运行中"
fi

# 检查用户是否存在
if id "www-data" &>/dev/null; then
    echo "用户存在"
fi

# 检查目录是否为空
if [ -z "$(ls -A /tmp/test 2>/dev/null)" ]; then
    echo "目录为空"
fi

六、实战示例 #

6.1 参数检查脚本 #

bash
#!/bin/bash

# 检查参数数量
if [ $# -lt 1 ]; then
    echo "用法: $0 <文件路径>"
    exit 1
fi

file="$1"

# 检查文件是否存在
if [ ! -e "$file" ]; then
    echo "错误: 文件 $file 不存在"
    exit 1
fi

# 检查文件类型
if [ -f "$file" ]; then
    echo "文件类型: 普通文件"
elif [ -d "$file" ]; then
    echo "文件类型: 目录"
elif [ -L "$file" ]; then
    echo "文件类型: 符号链接"
else
    echo "文件类型: 其他"
fi

# 检查权限
if [ -r "$file" ] && [ -w "$file" ]; then
    echo "权限: 可读可写"
elif [ -r "$file" ]; then
    echo "权限: 只读"
else
    echo "权限: 无"
fi

6.2 用户输入验证 #

bash
#!/bin/bash

read -p "请输入用户名: " username
read -s -p "请输入密码: " password
echo ""

# 验证用户名
if [[ -z "$username" ]]; then
    echo "错误: 用户名不能为空"
    exit 1
fi

if (( ${#username} < 3 )); then
    echo "错误: 用户名至少3个字符"
    exit 1
fi

# 验证密码
if [[ -z "$password" ]]; then
    echo "错误: 密码不能为空"
    exit 1
fi

if (( ${#password} < 6 )); then
    echo "错误: 密码至少6个字符"
    exit 1
fi

echo "验证通过"

6.3 系统检查脚本 #

bash
#!/bin/bash

check_system() {
    echo "=== 系统检查 ==="
    
    # 检查root权限
    if [ "$(id -u)" -eq 0 ]; then
        echo "[警告] 正在以root用户运行"
    fi
    
    # 检查磁盘空间
    local usage=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
    if (( usage > 80 )); then
        echo "[警告] 磁盘使用率超过80%: ${usage}%"
    else
        echo "[正常] 磁盘使用率: ${usage}%"
    fi
    
    # 检查内存
    local mem_free=$(free -m | awk 'NR==2 {print $7}')
    if (( mem_free < 100 )); then
        echo "[警告] 可用内存不足100MB: ${mem_free}MB"
    else
        echo "[正常] 可用内存: ${mem_free}MB"
    fi
    
    # 检查必要命令
    local commands=("git" "curl" "vim")
    for cmd in "${commands[@]}"; do
        if ! command -v "$cmd" &>/dev/null; then
            echo "[警告] 命令 $cmd 未安装"
        else
            echo "[正常] 命令 $cmd 已安装"
        fi
    done
}

check_system

七、if语句最佳实践 #

7.1 代码风格 #

bash
#!/bin/bash

# 推荐:then单独一行
if [ condition ]
then
    # 代码
fi

# 推荐:分号形式
if [ condition ]; then
    # 代码
fi

# 推荐:使用 [[ ]] 代替 [ ]
if [[ condition ]]; then
    # 代码
fi

# 推荐:变量加引号
if [[ -n "$var" ]]; then
    # 代码
fi

7.2 避免常见错误 #

bash
#!/bin/bash

# 错误:变量未加引号
# [ $str = "hello" ]  # 如果str为空会报错

# 正确:变量加引号
[ "$str" = "hello" ]

# 错误:在 [ ] 中使用 && 和 ||
# [ $a -gt 0 && $b -gt 0 ]  # 错误

# 正确:使用 -a 和 -o
[ $a -gt 0 -a $b -gt 0 ]

# 或者使用 [[ ]]
[[ $a -gt 0 && $b -gt 0 ]]

# 或者分开写
[ $a -gt 0 ] && [ $b -gt 0 ]

八、总结 #

8.1 if语句要点 #

要点 说明
基本结构 if [ condition ]; then … fi
多分支 if … elif … else … fi
推荐写法 使用 [[ ]] 和 (( ))
条件组合 使用 &&
变量引用 始终使用双引号

8.2 下一步 #

你已经掌握了if条件判断,接下来让我们学习 case语句,了解多分支选择结构!

最后更新:2026-03-27