Shell脚本中if、switch 条件判断使用

shell 2023-07-15 295次浏览

前言

在Shell脚本中,可以使用if语句和case语句来进行条件判断和分支控制,类似于其他编程语言中的if-else和switch语句。以下是示例代码介绍:

1. if语句的使用:

if [ condition1 ]; then
    # code to execute when condition1 is true
elif [ condition2 ]; then
    # code to execute when condition2 is true
else
    # code to execute when all conditions are false
fi

condition1condition2 是需要评估的表达式,可以使用比较运算符和逻辑运算符构建条件判断。elif和else是可选的。

2. case语句的使用:

case $variable in
    pattern1)
        # code to execute when variable matches pattern1
        ;;
    pattern2)
        # code to execute when variable matches pattern2
        ;;
    *)
        # code to execute when variable does not match any pattern
        ;;
esac

variable 是需要匹配的变量,pattern1pattern2 是通配模式,可以使用 *?[...] 等进行匹配。;; 表示匹配成功后结束该分支的执行。

3. 示例代码

结合if和case的示例代码,用于展示如何使用条件判断和分支控制:

#!/bin/bash

fruit="apple"

if [ $fruit == "banana" ]; then
    echo "It is a banana"
elif [ $fruit == "apple" ]; then
    echo "It is an apple"
else
    echo "It is neither a banana nor an apple"
fi

case $fruit in
    "banana")
        echo "It is a banana"
        ;;
    "apple")
        echo "It is an apple"
        ;;
    *)
        echo "It is neither a banana nor an apple"
        ;;
esac

运行以上脚本将输出:

It is an apple
It is an apple

Shell脚本中if、switch 条件判断使用

喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址