Getting Yes or No Input

Problem

You need to get a simple yes or no input from the user, and you want to be as user-friendly as possible. In particular, you do not want to be case sensitive, and you want to provide a useful default if the user presses the Enter key.

Solution

If the actions to take are simple, use this self-contained function:

# cookbook filename: func_choose

# Let the user make a choice about something and execute code based on
# the answer
# Called like: choose <default (y or n)> <prompt> <yes action> <no action>
# e.g. choose "y" \
#       "Do you want to play a game?" \
#       /usr/games/GlobalThermonucularWar \
#       'printf "%b" "See you later Professor Falkin.\n"' >&2
# Returns: nothing
function choose {

    local default="$1"
    local prompt="$2"
    local choice_yes="$3"
    local choice_no="$4"
    local answer

    read -p "$prompt" answer
    [ -z "$answer" ] && answer="$default"

    case "$answer" in
        [yY1] ) eval "$choice_yes"
            # error check
            ;;
        [nN0] ) eval "$choice_no"
            # error check
            ;;
        *     ) printf "%b" "Unexpected answer '$answer'!" >&2 ;;
    esac
} # end of function choose

If the actions are complicated, use this function and handle the results in your main code.

# cookbook filename: func_choice.1 # Let the user make a choice about something and return a standardized # answer. How the default is handled and what happens next is up to # the if/then after the choice in main # Called like: choice <promtp> # e.g. choice "Do you want to play a game?" # Returns: global variable CHOICE function choice { CHOICE='' ...

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.