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 do and the done) and then re-prompt you for the next value.

It doesn’t redisplay the list every time, only if you make no choice and just press the Enter key. So whenever you want to see the list again, just press Enter.

It does not re-evaluate the code after the in, that is, you can’t alter the list once you’ve begun. If you modified $DBLIST inside the loop, it wouldn’t change your list of choices.

The looping will stop when it reaches the end of the file, which for interactive use means when you type Ctrl-D. (If you piped a series of choices into a select loop, it would end when the input ends.)

There isn’t any formatting control over the list. If you’re going to use select, you have to be satisfied with the way it displays your choices. You can, however, alter the prompt on the select.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.150.41