bash - select: accept an unlisted, char input -
i'm using bash
select
make multiple choice dialog in option numbers adjust automatically when add new selection between 2 existing ones.
select choice in command1 command2 command3; $choice break done
to display different command executed in itself, i've been told declare associative array
declare -a choices=( [option 1]=command1 [option 2]=command2 [option 3]=command3 ) select choice in "${!choices[@]}" exit ; [[ $choice == exit ]] && break ${choices[$choice]} done
the thing don't way, option exit
viewed numbered selection. i'd want achieve like
ps3="select desired option (q quit): "
and make select
accept q
, besides 1
, 2
or 3
, valid input.
the associative array causes problems fact input used index, switched nested case
. way, not have declare separate functions store more 1 command
ps3="select desired option (q quit): " select choice in "option 1" "option 2" "option 3"; case $choice in "option 1") command1a command1b break;; "option 2") command2a command2b break;; "option 3") command3a command3b break;; q) echo "bye!" break;; esac done
now there no problems regarding non-numerical (or over-range) input, q
input still not recognized. falls in the default
case, executing *)
if have defined it, or prompting again if didn't.
is there way achieve i'm trying do?
just use (check content of) $reply
variable.
example:
declare -a choices=( [show date]=show_date [print calendar]=print_cal [say hello]=say_hello ) show_date() { date } print_cal() { cal } say_hello() { echo "hello $user" } ps3="select desired option (q quit): " select choice in "${!choices[@]}" case "$choice" in '') # handling invalid entry - e.g. "q" # in case of invalid entry, $choice en empty(!) string # checking content of entered line can done using $reply case "$reply" in q|q) echo "bye, bye - quitting...."; exit;; *) echo "invalid choice <$reply> - try again";; esac ;; *) #valid user input ${choices[$choice]} ;; esac done
or shorter, not flexible
declare -a choices=( [show date]=show_date [print calendar]=print_cal [say hello]=say_hello ) show_date() { date } print_cal() { cal } say_hello() { echo "hello $user" } ps3="select desired option (q quit): " select choice in "${!choices[@]}" case "$reply" in q|q) echo "bye, bye - quitting...."; exit;; 1|2|3) ${choices[$choice]} ;; *) echo "invalid choice <$reply> - try again";; esac done
Comments
Post a Comment