0

I have an dynamic number of options for a user prompt, and if possible would like manage the actions for each through a case statement.

Besides the dynamic number of options, the pattern will be build dynamically, and also the actions to do inside of each pattern. I understand that a loop has to be used inside the case statement, but I can't figure how to do this trick (even whether is possible)

An basic example of the idea:

totalitems=5    
for ((c_a=1;c_a<=totalitems;c_a++)) 
do  
    echo "option $c_a"                                          
done

read -n 1 -p "Choose an option from: 1 to $c_a" answer  

case "$answer" in       

#for ((c_a=1;c_a<=totalitems;c_a++))
#do 
  $c_a)
   echo "$c_a"     
;;          
#done 

  *) echo "invalid option!"
    sleep 1
    exit;;
esac
Daniel Perez
  • 431
  • 5
  • 11
  • 2
    A `case` statement is only good for a fixed list of options. For a dynamic list you'll need to roll your own handling. – John Kugelman Apr 15 '20 at 17:28
  • I'd strongly recommend using a convention for function naming for this purpose. `menuoption__foo() { ...; }`, to run the code `...`, then can be displayed as `foo` -- defining a function is sufficient to add to the menu. I believe there already SO Q&A entries describing how to implement that kind of pattern; much like how creating a program named `git-something` defines a command that can be run as `git something`. – Charles Duffy Apr 15 '20 at 17:28
  • ...it's also easy, once you did a search for functions whose names start with `menuoption__`, to search for variables with other metadata; once you know `menuoption__foo` exists as a function, you can look at whether there's a string named `menuoption__foo__desc` with the description to show in your menu, f/e. – Charles Duffy Apr 15 '20 at 17:31
  • ...see [Listing defined functions in bash](https://stackoverflow.com/questions/2625783/listing-defined-functions-in-bash) for the initial (actually-finding-the-functions) end of it. – Charles Duffy Apr 15 '20 at 17:31

1 Answers1

0

When you have less than 10 items, you can do

#!/usr/bin/env bash

totalitems=5
for ((c_a=1;c_a<=totalitems;c_a++)) 
do
    echo "option $c_a"                                          
done

read -en 1 -p "Choose an option from: 1 to $totalitems : " answer

case "$answer" in       
  [1-$totalitems]) echo "$answer";;  
  *) echo "invalid option!"
    sleep 1
    exit;;
esac
Philippe
  • 20,025
  • 2
  • 23
  • 32
  • i suppose it will work for my basic and defective code example, but i need a loop and enable dynamic generation of patterns. The purpose is more complex than my example, the pattern will not be numeric or consecutive characters. thanks – Daniel Perez Apr 17 '20 at 16:33