Endless select menu in bash script

Printer-friendly versionPDF version

 

There are many sources on the web for creating menus in bash scripts. After prodding through the many examples, I am documenting the approach that I felt was generic enough for all my intents and pusposes. Just as a reference even to me, in case I need to do it again.

#!/bin/bash
function myfunc1() {
}
 
function myfunc2() {
}
 
function myfunc3() {
}
 
function echoMenu() {
    echo "******************************************************************"
    echo "Please select an option"     
    options=(
             "Call My func 1"
             "Call My func 2"
             "Call My func 3"
        )
    select opt in "${options[@]}" "Quit"; do
        case "$REPLY" in
            1)
                myfunc1
                echoMenu
                ;;
            2)  
                myfunc2
                echoMenu
                ;;
            3)
                myfunc3
                echoMenu            
                ;;
            $(( ${#options[@]}+1 )) ) echo "Goodbye!"; exit;;
            *) echo "Invalid option. Try another one.";continue;;
        esac
    done  
}
 
echoMenu

The above will print the menu and keep on looping the menu till you explicitly type in the menu number entry for exit. The good thing is exit does not have an entry menu number, it is the last one always. And you can keep augmenting your menu list as you wish, both on options and the case statements and you donot need to adjust quit. Ofcourse downside is when you move something or place something in between you have to adjust top to bottom from the change onwards.

 

 

Tags:

Top level category:

Add new comment