我正在尝试生成动态菜单,然后选择要保存在变量中的选项。到目前为止,我有这个,但我被卡住了。 它总是默认为
“ERROR选择不在列表中,重新运行脚本。”
IFACES=$(nmcli -t -f SSID dev wifi list | grep i)
SELECTION=1
while read -r line; do
echo "$SELECTION) $line"
((SELECTION++))
done <<< "$IFACES"
((SELECTION--))
echo
printf 'Select an interface from the above list: '
read -r OPT
if [[ `seq 1 $SELECTION` = $OPT ]]; then
sed -n "${OPT}p" <<< "$IFACES"
IFACE=$(sed -n "${OPT}p" <<< "$IFACES") #set interface
else
echo "ERROR Selection not in list, rerun the script."
exit 0
fi
答案 0 :(得分:2)
试试这个:
$ 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
将printf
替换为nmcli ...
命令。