动态生成的bash菜单

动态生成的bash菜单,bash,dynamic,menu,selection,Bash,Dynamic,Menu,Selection,我试图生成一个动态菜单,然后选择要保存在变量中的选项。到目前为止,我有这个,但我被卡住了。 不知何故,它总是默认为 错误选择不在列表中,请重新运行脚本 IFACES=$(nmcli-t-f SSID-dev-wifi列表| grep i) 选择=1 而read-r行;做 回显“$选择)$行” ((选择++)) 完成尝试以下操作: $ cat tst.sh mapfile -t ifaces < <(printf 'foo\nbar code\nstuff\nnonsense\n')

我试图生成一个动态菜单,然后选择要保存在变量中的选项。到目前为止,我有这个,但我被卡住了。 不知何故,它总是默认为

错误选择不在列表中,请重新运行脚本

IFACES=$(nmcli-t-f SSID-dev-wifi列表| grep i)
选择=1
而read-r行;做
回显“$选择)$行”
((选择++))
完成尝试以下操作:

$ cat tst.sh
mapfile -t ifaces < <(printf 'foo\nbar code\nstuff\nnonsense\n')
for i in "${!ifaces[@]}"; do
    printf "%s) %s\n" "$i" "${ifaces[$i]}"
done
printf 'Select an interface from the above list: '
IFS= read -r opt
if [[ $opt =~ ^[0-9]+$ ]] && (( (opt >= 0) && (opt <= "${#ifaces[@]}") )); then
    printf 'good\n'
else
    printf 'bad\n'
fi

用你的
nmcli…
命令替换
printf

你认为
seq 1$SELECTION
doesIt打印的数字序列不超过$SELECTION。好吧,那么“$OPT”(特定数字)怎么可能等于“1 2 3 4 5…”呢?我现在明白了。再次感谢。你知道“选择”命令吗?谢谢你,Ed,我是新手。不客气。在开始编写shell脚本之前,你需要得到一些基础,因为它非常容易出错,而且bug经常是阴险的,后果是灾难性的,所以请尝试阅读克里斯·约翰逊的shell脚本脚本,并在这里搜索Stephane Chazelas或Charles Duffy的BASH答案。(也有其他人提供了准确的答案,但有很多“答案”完全是胡说八道,这是我的两个目标)。再次感谢Ed,我会的。
$ cat tst.sh
mapfile -t ifaces < <(printf 'foo\nbar code\nstuff\nnonsense\n')
for i in "${!ifaces[@]}"; do
    printf "%s) %s\n" "$i" "${ifaces[$i]}"
done
printf 'Select an interface from the above list: '
IFS= read -r opt
if [[ $opt =~ ^[0-9]+$ ]] && (( (opt >= 0) && (opt <= "${#ifaces[@]}") )); then
    printf 'good\n'
else
    printf 'bad\n'
fi
$ ./tst.sh
0) foo
1) bar code
2) stuff
3) nonsense
Select an interface from the above list: d
bad

$ ./tst.sh
0) foo
1) bar code
2) stuff
3) nonsense
Select an interface from the above list: 5
bad

$ ./tst.sh
0) foo
1) bar code
2) stuff
3) nonsense
Select an interface from the above list: 3
good