Bash 中使用 select 制作菜单
在本教程中,我们将介绍 Bash 中的 select
结构的基础知识。
select
结构允许您生成菜单。
select
的用法
select
结构从条目列表中生成菜单。它与 for
循环的语法几乎相同:
select ITEM in [LIST]
do
[COMMANDS]
done
其中 [LIST]
可以是一系列由空格隔开字符串序列,数字序列,一个命令的输出,一个数组等等。 select
使用 PS3
环境变量设置自定义提示信息。
调用 select
时,列表中的每个条目都会打印在屏幕上,并带有数字编号。
如果用户输入的数字与显示的条目之一的编号相对应,则将 [ITEM]
的值设置为数字编号对应的条目。所选条目的编号值存储在 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:
select
示例
通常情况下, select
会结合使用 case
或者 if
语句。
让我们看一个更实际的例子。它是一个简单的计算器,可以提示用户输入并执行基本的算术运算,例如加法,减法,乘法和除法。
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
工具来执行数学计算。同样,重复代码是现在一个 function 中。
calculate () {
read -p "Enter the first number: " n1
read -p "Enter the second number: " n2
echo "$n1 $1 $n2 = " $(bc -l <<< "$n1$1$n2")
}
PS3="Select the operation: "
select opt in add subtract multiply divide quit; do
case $opt in
add)
calculate "+";;
subtract)
calculate "-";;
multiply)
calculate "*";;
divide)
calculate "/";;
quit)
break;;
*)
echo "Invalid option $REPLY";;
esac
done
1) add
2) subtract
3) multiply
4) divide
5) quit
Select the operation: 4
Enter the first number: 8
Enter the second number: 9
8/9 = .88888888888888888888
Select the operation: 5
结论
select
结构使您可以轻松生成菜单。在编写需要用户选择输入的 shell 脚本时,它特别有用。