Bash Select(生成菜单)

时间:2020-03-05 15:31:38  来源:igfitidea点击:

在本教程中,我们将介绍Bash中select构造的基础知识。

select构造允许您生成菜单。

Bash选择构造

select构造从项目列表生成一个菜单。
它的语法与for循环几乎相同:

select ITEM in [LIST]
do
  [COMMANDS]
done

[LIST]可以是一系列由空格分隔的字符串、一个数字范围、一个命令的输出、一个数组等等。
可以使用PS3环境变量设置select构造的自定义提示。

调用select构造时,列表中的每个项目都会打印在屏幕上(标准错误),前面有一个数字。

如果用户输入一个与所显示项目的编号相对应的数字,则[项目]的值被设置为该项目。
所选项目的值存储在变量REPLY中。
否则,如果用户输入为空,则再次显示提示和菜单列表。

select循环将继续运行并提示用户输入,直到执行break命令为止。

为了演示select构造的工作原理,让我们看一下下面的简单示例:

PS3="Enter a number: "

select character in Sheldon Leonard Penny Howard Raj
do
    echo "Selected character: $character"
    echo "Selected number: $REPLY"
done

该脚本将显示一个菜单,其中包含一个带有编号的列表项和PS3提示符。
当用户输入数字时,脚本将打印所选字符和数字:

1) Sheldon
2) Leonard
3) Penny
4) Howard
5) Raj
Enter a number: 3
Selected character: Penny
Selected number: 3
Enter a number:

Bash选择示例

通常,select与if语句的case结合使用。

让我们看一个更实际的例子。
它是一个简单的计算器,提示用户输入并执行基本的算术运算,如加法、减法、乘法和除法。

PS3="Select the operation: "

select opt in add subtract multiply divide quit; do

  case $opt in
    add)
      read -p "Enter the first number: " n1
      read -p "Enter the second number: " n2
      echo "$n1 + $n2 = $(($n1+$n2))"
      ;;
    subtract)
      read -p "Enter the first number: " n1
      read -p "Enter the second number: " n2
      echo "$n1 - $n2 = $(($n1-$n2))"
      ;;
    multiply)
      read -p "Enter the first number: " n1
      read -p "Enter the second number: " n2
      echo "$n1 * $n2 = $(($n1*$n2))"
      ;;
    divide)
      read -p "Enter the first number: " n1
      read -p "Enter the second number: " n2
      echo "$n1/$n2 = $(($n1/$n2))"
      ;;
    quit)
      break
      ;;
    *) 
      echo "Invalid option $REPLY"
      ;;
  esac
done

执行脚本时,它将显示菜单和PS3提示符。
系统会提示用户选择操作,然后输入两个数字。
根据用户的输入,脚本将打印结果。
每次选择后,用户将被要求执行新操作,直到执行break命令为止。

1) add
2) subtract
3) multiply
4) divide
5) quit
Select the operation: 1
Enter the first number: 4
Enter the second number: 5
4 + 5 = 9
Select the operation: 2
Enter the first number: 4
Enter the second number: 5
4 - 5 = -1
Select the operation: 9
Invalid option 9
Select the operation: 5

这个脚本的一个缺点是它只能处理整数。

这里有一个更高级的版本。
我们使用支持浮点数的bc工具来执行数学计算。
同样,重复的代码被分组在一个函数中。