How do I make a menu?

Some people like to use select because it's simple. If your own needs are extremely simple, then this may be sufficient for you. If you want your own look and feel, you can simply write a menu yourself. There is also dialog, which we won't cover on this page.

Using select

To use select, you need a list of choices. select will automatically assign numbers to the choices, and issue a prompt. You may customize the prompt.

$ PS3='¿Qué es más macho? '
$ select ch in schoolbus lightbulb; do echo "You have chosen $ch!"; break; done
1) schoolbus
2) lightbulb
¿Qué es más macho? 45
You have chosen !
$ select ch in schoolbus lightbulb; do echo "You have chosen $ch!"; break; done
1) schoolbus
2) lightbulb
¿Qué es más macho? 2
You have chosen lightbulb!

If you check for an "empty" (invalid) selection inside the loop, then it becomes slightly less horrible:

$ select ch in schoolbus lightbulb; do if [[ $ch ]]; then echo "You have chosen $ch!"; break; fi; done
1) schoolbus
2) lightbulb
¿Qué es más macho? 45
¿Qué es más macho? 0
¿Qué es más macho? 2
You have chosen lightbulb!

And that's select. Moving on....

Writing your own menu

Just make a loop using echo and read. It's really that simple. Let's spice it up by making a multi-level menu application instead.

   1 #!/bin/bash
   2 
   3 main() {
   4   while true; do
   5     echo "== Make your selection:"
   6     echo "a) add"
   7     echo "s) subtract"
   8     echo "m) multiply"
   9     echo "q) quit"
  10     while true; do
  11       read -r -n1 -p "> " ch
  12       echo
  13       case $ch in
  14         a) add; break;;
  15         s) subtract; break;;
  16         m) multiply; break;;
  17         q) exit 0;;
  18         *) echo "Unrecognized command.  Please try again.";;
  19       esac
  20     done
  21   done
  22 }
  23 
  24 add() {
  25   local a b
  26   while true; do
  27     echo "== Addition"
  28     echo "Enter first addend, or q to return to main menu."
  29     read -r -p "> " a
  30     [[ $a = q ]] && return
  31     echo "Enter second addend."
  32     read -r -p "> " b
  33     echo "$a + $b = $((a + b))"
  34   done
  35 }
  36 
  37 # subtract and multiply functions not shown
  38 
  39 main

You can make it as simple or as complex as you like. You can create your own input function to wrap read and persist until the user types a syntactically valid response. You can use read -e to allow the user to use readline editing features. It's all up to you.

BashFAQ/115 (last edited 2017-03-14 18:43:12 by GreyCat)