Creating Multiple Menus in Bash Scripts

I have been writing a couple of scripts now for different use cases, wouldn’t it be handy to build a menu which will provide a list of command select to choose from? e.g It can contain all sorts of script in one mega script.

Basically, the menu will loop until the user chooses to exit from the menu, consider the following example:

					

while true
do
---------
---------
done

The loop above is an infinite loop, and it won’t stop until we break it. The true command will always return true and loop continousoly, don’t worry, we would build a logic on how user can exit the menu.

To start with the structure, we will need to print some text to the STDOUT (the screen) asking the user for their choice of command. We will clear the screen before the menu is loaded each time and an additional read prompt will appear after the execution of the desired command.

Consider the following example:

					

#!/bin/bash
# Multi-Mega Script
# Author: The_Devsrealm_Guy
# Date: September, 2020
# Website: https://devsrealm.com

while true
do
 clear
 echo "Choose an item: a,b or c"
 echo "a: Replace Multi Occurrences of A String in Files"
 echo "b: Backup"
 echo "c: Exit"
 read -sn1
 read -n1 -p "Press any key to continue"
done

If you execute this script as is, there will be no mechanism to leave the
script. We have not added any code to the menu selections; however, you can force exit using Ctrl + c key.

The read -n1 -p limit the user to only accept 1 character, so, no matter what you enter, you’ll always see “Press any key to continue”, so, again, exit using Ctrl + C

To build the script behind the menu selection, we will implement a case statement as follows:

					

#!/bin/bash
# Multi-Mega Script
# Author: The_Devsrealm_Guy
# Date: September, 2020
# Website: https://devsrealm.com

while true
do
 clear
 echo "Choose an item: a,b or c"
 echo "a: Ask My Name"
 echo "b: Show me Date"
 echo "c: Backup my home directory"
 echo "d: Exit"
 read -sn1
case "$REPLY" in
a) 
read -p "What is Your Name? " name
echo "Your Name is $name"
;;
b) date
;;
c)tar -czvf $HOME/backup.tgz ${HOME}/bin
;;
d) exit 0
;;
esac
 read -n1 -p "Press any key to continue"
done

Note: read -sn1 is used to suppress whatever you input

We added four options to the case statement, a, b, c, and d:

  • Option a: This asks for user name, and prints out the name
  • Option b: This runs the date command to display the current date
  • Option c: This runs the tar command to back-up the scripts
  • Option d:  This exits the script

Comment policy: Respectful and beneficial comments are welcome with full open hands. However, all comments are manually moderated and those that doesn't relate with what the passage is saying or offensive comments would be deleted. Thanks for understanding!

Leave a Reply

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