在本教程中,我们将介绍以下基础知识select
在 Bash 中构建。
The select
构造允许您生成菜单。
Bash select
构造#
The select
构造从项目列表生成菜单。它的语法几乎与for
loop:
select ITEM in [LIST]
do
[COMMANDS]
done
The [LIST]
可以是一系列由空格分隔的字符串、数字范围、命令的输出、数组等。自定义提示select
构造可以使用设置PS3
环境变量
.
当。。。的时候select
调用构造后,列表中的每个项目都会打印在屏幕上(标准错误),前面带有一个数字。
如果用户输入的数字与所显示项目之一的编号相对应,则[ITEM]
被设置为该项目。所选项目的值存储在变量中REPLY
。否则,如果用户输入为空,则再次显示提示和菜单列表。
The 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
迅速的。当用户输入数字时,脚本将print所选字符和数字:
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
例子#
通常,select
与以下组合使用case
of 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
结论#
The select
构造允许您轻松生成菜单。当编写需要用户输入的 shell 脚本时,它特别有用。
如果您有任何问题或反馈,请随时发表评论。