【发布时间】:2022-01-09 13:50:24
【问题描述】:
以下提示应允许用户根据输出到数组的填充列表进行选择,然后打印列表及其索引,并要求用户从列表中选择一个数字,然后将其设置为多变的。只允许一个选项,如果用户指定的选项不正确,脚本会提示选择正确的数字。
Multiple devices detected, please select one from the list:
1. Device1
2. Device2
3. Device3
1
You have selected device Device1
下面的代码不起作用并且有很多语法错误,首先我想让脚本检测arr=($(ip ad|awk '/state UP/ {print $2}'))的输出是否包含多个条目,如果是则运行脚本,否则设置一个默认值。
case 语句不是动态的,但是如果超过 2 个类似下面的 case 就会失败,也许是一个循环?
host_interfaces()
{
arr=($(ip ad|awk '/state UP/ {print $2}'))
echo "Multiple devices detected, please select one from the list:"
for i in "${!arr[@]}"; do
printf "%s%s\n" "$i. " "${arr[$i]}"
done
PS3='Please enter your choice: '
select opt in "${arr[@]}"
do
case $opt in
"$opt")
echo "You have selected device $opt"
export HOST_INTERFACE=$opt
;;
*) echo "invalid option
break
;;
esac
done
}
【问题讨论】:
-
${#arr[@]}扩展为数组中的条目数。所以[ "${#arr[@]}" -eq 1 ]也许是你正在寻找的测试。 -
我不确定我是否了解所有细节。当你的用户选择一个有效的选项时,你想做什么?继续要求选择还是停在那里? Same question when the choice is not valid or when the choice corresponds to
Quit. -
试试
dialog/whiptail -
@RenaudPacalet 当用户选择一个有效选项时,该值设置为 HOST_INTERFACE 并且函数结束。我删除了“退出”,因为它是示例代码 sn-p 的一部分,因此唯一的选项是数组中的有效选择或无效选择。
-
@Kev 好的,我相应地更新了我的答案。请编辑您的问题并修改它以反映您的真实规格(SO 对其他有类似问题的访问者也很有用,因此问题非常清晰和准确很重要)。
标签: linux bash loops shell scripting