shell script main menu submenu

How to Create Menu with Submenu in Shell Script

Shell Scripts are very useful in automating tasks & processes in Linux. Sometimes you may need to create menu with submenu in shell script. In this article, we will learn how to create such interactive shell scripts in Linux. You can use these steps in almost every Linux.


How to Create Menu with Submenu in Shell Script

Basically, interactive shell scripts run a do…while loop or some other loop, that terminates only with specific user input. Here is a simple prototype of shell script that employs main menu & submenu.

#!/bin/bash

# submenu
submenu () {
  local PS3='Please enter sub option: '
  local options=("1" "2" "quit")
  local opt
  select opt in "${options[@]}"
  do
      case $opt in
          "1")
              echo "you chose sub item 1"
              ;;
          "2")
              echo "you chose sub item 2"
              ;;
          "quit")
              return
              ;;
          *) echo "invalid option $REPLY";;
      esac
  done
}

# main menu
PS3='Please enter main option: '
options=("Main menu item 1" "Submenu" "exit")
select opt in "${options[@]}"
do
    case $opt in
        "Main menu item 1")
            echo "you chose main item 1"
            ;;
        "Submenu")
            submenu
            ;;
        "exit")
            exit
            ;;
        *) echo "invalid option $REPLY";;
    esac
done

Let us look at the above code in detail. First, we define the execution environment. Next, we define submenu() function that displays the submenu. It prompts the user to enter submenu option and displays the 3 submenu options. Based on the user input, it uses a switch case statement to execute the appropriate block of code for the selected option. The last option will exit the submenu and bring control back to main menu. You can always add more submenu options as per your requirement.

Next, we have defined the main menu. Here too, the shell script will prompt the user for input. The first option(Main menu item 1) displays the user input, second option(submenu) displays submenu options and the 3 option(exit) exits the script. Here too, you can add more menu options to work with multiple submenus.

That’s it. In this short article, we have learnt how to create main menu with submenu in shell script.

Also read:

How to Delete File in Git Repository
What does __file__ mean in Python
Sed Command to Replace String in File
What is __name__ in Python
How to Find Non-ASCII characters in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *