📜  Linux 中的 case 命令及示例(1)

📅  最后修改于: 2023-12-03 15:32:40.928000             🧑  作者: Mango

Linux 中的 case 命令及示例

case 命令是 Linux shell 中的一个条件语句结构,用于对变量的取值进行分类,类似于 switch/case 语句。使用 case 命令可以简化代码,并提高可读性。

语法

case 命令的基本语法如下:

case expression in
pattern1) command1;;
pattern2) command2;;
pattern3) command3;;
esac

其中,expression 是需要进行分类的变量名或表达式,pattern 是用于匹配 expression 的模式,command 则是需要执行的命令语句。

case 命令执行的流程如下:

  1. case 命令将 expression 与每个 pattern 进行匹配,如果匹配成功,则执行对应的 command,然后退出。
  2. 如果没有匹配成功,则执行默认的 command

pattern 可以是文本模式、正则表达式模式、范围模式等。

示例

以下是 case 命令的多种使用示例。

按照文本模式分类

以下示例将以一个文本变量为例,按照文本模式进行分类:

#!/bin/bash
echo -n "Enter the name of a country: "
read COUNTRY

case $COUNTRY in
"China"|"china")
  echo "Chinese"
  ;;
"Japan"|"japan")
  echo "Japanese"
  ;;
"Korea"|"korea")
  echo "Korean"
  ;;
*)
  echo "Sorry, I don't know this country."
  ;;
esac

在上述示例中,用户输入一个国家名称,case 命令将输入值与每个模式进行匹配,找到匹配项后输出相应的信息。

按照正则表达式模式分类

以下示例将以一个文本变量为例,按照正则表达式模式进行分类:

#!/bin/bash
echo -n "Enter a number between 1 and 10: "
read NUM

case $NUM in
[1-5])
  echo "The number is between 1 and 5."
  ;;
[6-9])
  echo "The number is between 6 and 9."
  ;;
10)
  echo "The number is 10."
  ;;
*)
  echo "Sorry, the number is not valid."
  ;;
esac

在上述示例中,用户输入一个数字,case 命令将输入值与每个正则表达式模式进行匹配,找到匹配项后输出相应的信息。

按照文件类型分类

以下示例将以一个文件为例,按照文件类型进行分类:

#!/bin/bash

FILE=$(readlink -f $1)

case $FILE in
*.txt)
  echo "The file is a text file."
  ;;
*.sh)
  echo "The file is a shell script."
  ;;
*.jpg|*.png|*.gif)
  echo "The file is a picture file."
  ;;
*)
  if [ -d $FILE ]; then
    echo "The file is a directory."
  else
    echo "The file type is not recognized."
  fi
  ;;
esac

在上述示例中,该脚本需要一个文件参数作为输入参数。case 命令将输入值与每个文件类型进行匹配,找到匹配项后输出相应的信息。

使用变量扩展

以下示例将以一个变量为例,使用变量扩展进行分类:

#!/bin/bash
VALUE=x
case ${VALUE,,} in
x)
  echo "The value is X."
  ;;
y)
  echo "The value is Y."
  ;;
z)
  echo "The value is Z."
  ;;
*)
  echo "Sorry, the value is unknown."
  ;;
esac

在上述示例中,该脚本使用变量扩展将变量名小写。case 命令将小写后的变量名与每个模式进行匹配,找到匹配项后输出相应的信息。

总结

以上是 case 命令的基本语法和多种使用示例。通过 case 命令,可以实现更加简洁的代码和更高的可读性。在编写 Linux shell 脚本时,合理使用 case 命令可以帮助程序员更加高效地完成工作。