Creating Simple Menus

Problem

You have a simple SQL script that you would like to run against different databases to reset them for tests that you want to run. You could supply the name of the database on the command line, but you want something more interactive. How can you write a shell script to choose from a list of names?

Solution

Use the select statement to create simple character-based screen menus. Here’s a simple example:

#!/usr/bin/env bash
# cookbook filename: dbinit.1
#
DBLIST=$(sh ./listdb | tail -n +2)
select DB in $DBLIST
do
    echo Initializing database: $DB
    mysql -u user -p $DB <myinit.sql
done

Ignore for a moment how $DBLIST gets its values; just know that it is a list of words (like the output from ls would give). The select statement will display those words, each preceded by a number, and the user will be prompted for input. The user makes a choice by typing the number and the corresponding word is assigned to the variable specified after the keyword select (in this case DB).

Here’s what the running of this script might look like:

$ ./dbinit
1) testDB
2) simpleInventory
3) masterInventory
4) otherDB
#? 2
Initializing database: simpleInventory
#?
$

Discussion

When the user types “2” the variable DB is assigned the word simpleInventory. If you really want to get at the user’s literal choice, the variable $REPLY will hold it, in this case it would be “2”.

The select statement is really a loop. When you have entered a choice it will execute the body of the loop (between the ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.