whiptail require three numbers before continuing

I have this whiptail form that prompts for user input. Is there a way to force someone to enter three numbers, before allowing him to continue?

NUMBERS=$(whiptail --inputbox "Enter three numbers only" 8 78 000
--title "Three Numbers" 3>&1 1>&2 2>&3)

exitstatus=$? if [ $exitstatus = 0 ]; then
    echo "User selected Ok and entered " $NUMBERS else
    echo "User selected Cancel." fi

echo "(Exit status was $exitstatus)"

Answer

You can check what the user entered and run your whiptail in a loop until they enter a valid value:

#!/usr/bin/env bash

## I included the 000 in the regex below since
## you are populating your field with it. I assume you
## want 000 + 3 numbers.
until [[ $numbers =~ ^000[0-9]{3}$ ]]; do
        numbers=$(whiptail --inputbox "Enter three numbers only" 8 78 000 --title "Three Numbers" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ $exitstatus = 0 ]; then
                echo "User selected Ok and entered " $numbers
        else
                echo "User selected Cancel."
                break;
        fi
done

echo "(Exit status was $exitstatus)"

Note that I also changed the NUMBERS to numbers. As a general rule, avoid capital variable names in bash scripts since the global environment variables are in caps and that can lead to confusion.

Leave a Reply

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