Changing the Prompt on Simple Menus

Problem

You just don’t like that prompt in the select menus. How can it be changed?

Solution

The bash environment variable $PS3 is the prompt used by select. Set it to a new value and you’ll get a new prompt.

Discussion

This is the third of the bash prompts. The first ($PS1) is the prompt you get before most commands. (We’ve used $ in our examples, but it can be much more elaborate than that, including user ID or directory names.) If a line of command input needs to be continued, the second prompt is used ($PS2).

For select loops, the third prompt,$PS3, is used. Set it before the select statement to make the prompt be whatever you want. You can even modify it within the loop to have it change as the loop progresses.

Here’s a script similar to the previous recipe, but one that counts how many times it has handled a valid input:

#!/usr/bin/env bash
# cookbook filename: dbinit.2
#
DBLIST=$(sh ./listdb | tail -n +2)

PS3="0 inits >"

select DB in $DBLIST
do
    if [ $DB ]
    then
        echo Initializing database: $DB

        PS3="$((++i)) inits> "

        mysql -u user -p $DB <myinit.sql
    fi
done

We’ve added some extra whitespace to make the setting of $PS3 stand out more. The if statement assures us that we’re only counting the times when the user entered a valid choice. Such a check would be useful in the previous version, but we were keeping it simple.

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.