如何使用我存储在文本文件的各行中的选项为用户显示选择菜单?
例如,我的文本文件 (ingestion.txt) 如下所示。
SOUP
FTS/CTS
JDBC
NEW
我希望用户看到这个
Please select an option by typing in the corresponding number
1) SOUP
2) FTS/CTS
3) JDBC
4) NEW
然后,如果他们没有输入有效的号码,系统会再次提示他们。
#!/bin/bash
unset option menu ERROR # prevent inheriting values from the shell
declare -a menu # create an array called $menu
menu[0]="" # set and ignore index zero so we can count from 1
# read menu file line-by-line, save as $line
while IFS= read -r line; do
menu[${#menu[@]}]="$line" # push $line onto $menu[]
done < ingestion.txt
# function to show the menu
menu() {
echo "Please select an option by typing in the corresponding number"
echo ""
for (( i=1; i<${#menu[@]}; i++ )); do
echo "$i) ${menu[$i]}"
done
echo ""
}
# initial menu
menu
read option
# loop until given a number with an associated menu item
while ! [ "$option" -gt 0 ] 2>/dev/null || [ -z "${menu[$option]}" ]; do
echo "No such option '$option'" >&2 # output this to standard error
menu
read option
done
echo "You said '$option' which is '${menu[$option]}'"
这会逐行读取 ingestion.txt,然后将该行的内容推送到$menu
array. ${#variable}
给你的长度$variable
。当给定整个数组时("${array[@]}"
类似于"$@"
), 例如${#array[@]}
,您将获得该数组中的元素数量。因为 bash 是零索引的,所以该数字是您可以添加的第一个可用项目,在给定新定义的(因此为空)数组的情况下从零开始。
The menu()
函数循环访问菜单项并将其显示在屏幕上。
然后我们循环直到获得有效的输入。由于 bash 会将非数字解释为零,因此我们首先确定它是否实际上是一个(自然)数字,丢弃来自非数字的任何错误,然后我们实际上确保索引存在。如果这不是第一次迭代,我们会抱怨之前给出的无效输入。显示菜单,然后read
用户输入到$option
.
根据有效的选项索引,循环停止,然后代码返回索引及其相应的值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)