Menu driven scripts

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Chapter 10: Interactive ScriptsHomeGetting information about your system →
  • You use some sort of generic application menu everyday.
  • A menu is nothing but a list of commands presented to a user by a shell script.
  • For example, you can write a menu driven shell script to get the terminal information. The menu driven shell script works as "shortcuts to frequently used commands that avoid the user having to remember syntax".
  • Usually, you need to type the instructions or commands to complete the task.
  • Command input can be done with the help of menus.

Syntax

Create a shell script called menu.sh:-

#!/bin/bash
# A menu driven shell script sample template 
## ----------------------------------
# Step #1: Define variables
# ----------------------------------
EDITOR=vim
PASSWD=/etc/passwd
RED='\033[0;41;30m'
STD='\033[0;0;39m'
 
# ----------------------------------
# Step #2: User defined function
# ----------------------------------
pause(){
  read -p "Press [Enter] key to continue..." fackEnterKey
}
 
one(){
	echo "one() called"
        pause
}
 
# do something in two()
two(){
	echo "two() called"
        pause
}
 
# function to display menus
show_menus() {
	clear
	echo "~~~~~~~~~~~~~~~~~~~~~"	
	echo " M A I N - M E N U"
	echo "~~~~~~~~~~~~~~~~~~~~~"
	echo "1. Set Terminal"
	echo "2. Reset Terminal"
	echo "3. Exit"
}
# read input from the keyboard and take a action
# invoke the one() when the user select 1 from the menu option.
# invoke the two() when the user select 2 from the menu option.
# Exit when user the user select 3 form the menu option.
read_options(){
	local choice
	read -p "Enter choice [ 1 - 3] " choice
	case $choice in
		1) one ;;
		2) two ;;
		3) exit 0;;
		*) echo -e "${RED}Error...${STD}" && sleep 2
	esac
}
 
# ----------------------------------------------
# Step #3: Trap CTRL+C, CTRL+Z and quit singles
# ----------------------------------------------
trap '' SIGINT SIGQUIT SIGTSTP
 
# -----------------------------------
# Step #4: Main logic - infinite loop
# ------------------------------------
while true
do
 
	show_menus
	read_options
done

Save and close the file. Run it as follows:

chmod +x menu.sh
./menu.sh

Sample outputs:

Menu-driven-output.png

← Chapter 10: Interactive ScriptsHomeGetting information about your system →