ragouel
ragouel

Reputation: 169

Dynamically generated bash menu

I'm trying to generate a dynamic menu and then select the option that I want to save in a variable. So far I have this, but I'm stuck. It somehow always defaults to

"ERROR Selection not in list, rerun the script."

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

Upvotes: 2

Views: 3191

Answers (1)

Ed Morton
Ed Morton

Reputation: 203229

Try this:

$ 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

Replace the printf with your nmcli ... command.

Upvotes: 5

Related Questions