Your use of the
select loop is already on the right track, since it forms a continuous loop to keep prompting you. All you need to do is set up an appropriate function for each of the chosen options. Functions act like sub-scripts inside the main script, which can be called on whenever needed, like any other command.
Code:
#!/bin/bash
clear
opt1(){
echo "this is option one, with arguments: ${@:-none}"
:<other code for option one>
}
opt2(){
echo "this is option two, with arguments: ${@:-none}"
:<other code for option two>
}
op3(){
echo "this is option three, with arguments: ${@:-none}"
:<other code for option three>
}
PS3='Please enter your choice: '
options=("Run 1" "Walk 2" "Jog 3" "Quit")
select opt in "${options[@]}"
do
case $opt in
"Run 1")
echo "you chose choice 1"
opt1 arg1 arg2
;;
"Walk 2")
echo "you chose choice 2"
opt2 arg3
;;
"Jog 3")
echo "you chose choice 3"
opt3
;;
"Quit")
break
;;
*) echo invalid option;;
esac
done
Whenever a function terminates you'll still be inside the
select loop and ready for another run. Of course for minor actions you don't even need a function, just include them directly in the
case statement.
Functions can take $1..$n input arguments, just like any other script. Just don't confuse them with the main script's parameters; these are local to the function. I also recommend keeping your user variables locally scoped whenever possible (with the
declare or
local keywords).
The only other main requirement is that functions need to be set up
before they are used, so you'll usually find their declarations at the top of the script.
BTW, from the code posted so far, you seem to already have a pretty good handle on basic scripting practice. For once I see no major issues to criticize.
Edit: Actually I just noticed that there's an error in your
select loop.
$opt holds the
text string of the option selected, so you'd need to test for "Run 1", "Walk 2", in the
case statement. Or you can also use
$REPLY instead, which contains the
number of current selection. I've modified the code above to reflect this.
Edit2: I just realized that this post may not have clearly answered the posted question. Creating a sub-menu is as simple as putting another menu inside the appropriate function, which can of course call other functions, ad infinitum. Each function is essentially a self-contained module that can be accessed whenever you need it.