I'm running Linux 3.10.0-693.2.2.el7.x86_64, and for the life of me can't figure why this would happen. It appears to be a bug and shellchecker finds no issues.
#!/bin/bash
set -o nounset
### functions
options=(one two three)
select var in "${options[@]}"; do
# make sure it is a valid choice
if (( REPLY <= ${#options[@]} )) && [[ $REPLY =~ ^[0-9]+$ ]]; then
case $var in
one) exit;;
two) df -h /tmp;;
*) echo $var;;
esac
break
else
printf "Invalid selection.\n" >&2
fi
I used set -xv to trouble shoot, but here's the output without it. In production, the options[@] will be set by a command, and the number they return will be dynamic. So I want the menu to execute a command in *) on $var-- but I have to check for an out of bounds selection in REPLY. Here is the output.
$ bad_select.bash
1) one
2) two
3) three
#? 4
Invalid selection.
#? t
/home/lc5550358/bin/select_menu.wip: line 9: t: unbound variable
The t
that I typed? I can also avoid the unbound variable, but entering k=2
or var
(the latter is defined in the select). Why and what is the work around
(set -o nounset
is needed)?
if [[ $REPLY =~ ^[0-9]+$ ]] && (( $REPLY <= ${#options[@]} )); then
select
itself already make sure that the choice is valid? Or is the point that you want to print an error message if it is invalid?REPLY
isn't set if you make an invalid selection, and the arithmetic statement is informing you of that.declare -i
). I find the error message vague, but par for the course. Thanks everyone for helping me.