温馨提示×

shell if语句怎么写才对

小樊
82
2024-06-17 15:10:55
栏目: 编程语言

if 语句在 shell 脚本中的基本语法为:

if [ condition ]; then
    # code to be executed if condition is true
fi

其中 condition 是要判断的条件,可以是比较两个值、检查变量是否为空等等。如果 condition 的结果为 true,则执行 thenfi 之间的代码块。

例如,判断一个变量是否等于某个值:

fruit="apple"

if [ $fruit == "apple" ]; then
    echo "This is an apple"
fi

注意,if 语句中的条件表达式需要用方括号 [] 括起来,并且变量的值前后都需要空格。

0