Shell test 命令
Shell 循环控制 

Shell 条件判断

在Shell脚本中,条件判断是控制程序流程的重要部分,常用于根据不同的条件执行不同的代码块。Shell提供了多种方式来进行条件判断,主要使用 if 语句及其相关结构。


if 语句基本结构

if condition
then
    # 如果 condition 为真,则执行这里的代码块
    commands
fi

  • condition 可以是任何能返回状态码(0 或非0)的表达式或命令。

  • then 后面跟着要执行的命令块,当 condition 为真时执行。

  • fi 表示 if 语句的结束。


示例:

#!/bin/bash
# 定义一个变量
age=25
# 使用 if 判断年龄是否大于 18
if [ $age -gt 18 ]; then
    echo "You are an adult."
fi


if-else 结构


if condition
then
    # 如果 condition 为真,则执行这里的代码块
    commands_true
else
    # 如果 condition 为假,则执行这里的代码块
    commands_false
fi

当 condition 为真时执行 commands_true,否则执行 commands_false。


示例:

#!/bin/bash
# 定义一个变量
num=10
# 使用 if-else 判断变量是否大于 0
if [ $num -gt 0 ]; then
    echo "Number is positive."
else
    echo "Number is non-positive."
fi


if-elif-else 结构

if condition1
then
    # 如果 condition1 为真,则执行这里的代码块
    commands1
elif condition2
then
    # 如果 condition1 为假,且 condition2 为真,则执行这里的代码块
    commands2
else
    # 如果前面的条件都不满足,则执行这里的代码块
    commands_else
fi

  • elif 用于指定额外的条件检查。

  • else 用于处理所有条件都不满足的情况。


示例:

#!/bin/bash
# 定义一个变量
score=75
# 使用 if-elif-else 判断分数的等级
if [ $score -ge 90 ]; then
    echo "Grade: A"
elif [ $score -ge 80 ]; then
    echo "Grade: B"
elif [ $score -ge 70 ]; then
    echo "Grade: C"
else
    echo "Grade: F"
fi


多重条件判断

在复杂情况下,可以使用嵌套的 if 结构或逻辑运算符来实现更复杂的条件逻辑。


示例:

#!/bin/bash
# 定义两个变量
num1=10
num2=20
# 使用逻辑运算符实现复杂条件判断
if [ $num1 -eq 10 ] && [ $num2 -eq 20 ]; then
    echo "Both numbers are correct."
fi



注意事项

  • 在 Shell 中,条件判断通常使用方括号 [ ] 或双括号 [[ ]] 来执行测试和比较操作。方括号 [ ] 是 test 命令的别名,而双括号 [[ ]] 提供了更多的功能和安全性,推荐在大多数情况下使用 [[ ]]。

  • 字符串比较时,为了避免意外的问题,建议在变量使用时加上双引号,如 "$variable"。

  • 条件判断中使用的数值比较和逻辑运算符,与其他编程语言中的操作符相似,但需要注意 Shell 中的空格和语法规则。


通过这些条件判断结构,你可以在 Shell 脚本中根据不同的条件来执行不同的代码,实现灵活的程序控制流程。