Write a bash script to making a simple multi-level user menu using select

Select works using a provided list (for example, it can be a wildcard selection for files) and will give you a list, such as:

Select a file from the list:

1.) myfirst.file

2.) mysecond.file

You chose: mysecond.file

Clearly, a menu such as about is very trivial; it can be useful for utility functions and for repeatable subtasks like deleting users or modifying files/archives. 

Prerequisites

Select is already a part of the Bash shell, but it has a few less than obvious points. Select relies on three variables:

  • PS3: The prompt that’s echoed to the user before the menu is created
  • REPLY: The index of the item selected from the array
  • opt: The value of the item selected from the array—not the index

Technically, opt is not mandatory, but it is the value of the element being iterated by Select in our example. You could use another name and call it element, for example.

How to do it…

Let’s start our activity as follows:

Open a terminal and create a script called select_menu.sh with the following contents:

select_menu.sh

#!/bin/bash 
TITLE="Select file menu" 
PROMPT="Pick a task:" 
OPTIONS=("list" "delete" "modify" "create") 
function list_files() { 
	PS3="Choose a file from the list or type \"back\" to go back to the main: " 
	select OPT in *; do 
		if [[ $REPLY -le ${#OPT[@]} ]]; then 
			if [[ "$REPLY" == "back" ]]; then 
				return 
			fi 
			echo "$OPT was selected" 
		else 
			list_files 
		fi 
	done 
}

Execute the script using the following command:

$ bash select_menu.sh

Press 1 to enter the file list functionality. Enter the number of any files in the menu. Once satisfied, type “back” and press Enter to return to the main menu.

How script works…

Let’s understand our script in detail:

Creating the select_menu.sh script was trivial, but besides the use of select, some of the concepts should look familiar: functions, return, case statements, and recursion. 

The script enters the menu by calling the main_menu function and then proceeds to use select to generate a menu from the ${OPTIONS} array. The hard-coded variable named PS3 will output the prompt before the menu, and $REPLY contains the index of the item selected.

Pressing 1 and pressing Enter will cause select to walk through the items and then execute the list_files function. This function creates a submenu by using select for the second time to list all of the files in the directory. Selecting any directory will return a $OPT was selected message, but if back is entered, then the script will return from this function and call main_menu from within itself (recursion). At this point, you may select any items in the main menu.

0 Comments

Submit a Comment

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

Related Articles