1

I would like to ask for user input on multiple questions and then store the inputs inside variables but also making sure that the input entered for each question is not empty or else it repeats the question

So far I have

input() {
        if [ ! -z "$db*" ]; then
                echo "Nothing entered" >&2;
                return
        else
                break
        fi
}

read -ep 'Enter your name >> [y/N]: ' name &&
input
read -ep 'Enter your email >> [y/N]: ' email &&
input
read -ep 'Enter your password >> [y/N]: ' password
input

2 Answers 2

2

Use an until statement and check for non-empty with [:

until [ "$NAME" ]; do
  printf "Name: "
  read NAME
done

The [ "$VAR" ] construction of the test command allows you to test whether the variable is non-empty1.

Sign up to request clarification or add additional context in comments.

2 Comments

You can also use [[ $NAME ]], since you are already assuming bash with the -p option to read.
Thank you very much for suggesting until, I will read up some more on the command.
0

I'm using the following combination of read and eval where you call the input-function with a variable to save input in and a message to be printed (input_not_empty "INPUTVAR" "message")

input()
{
    local foo
    echo -n "$2: "
    read foo
    eval "$1=\"$foo\""
}

input_not_empty()
{
    input $1 "$2"
    if [ -z "$(eval echo \$$1)" ]; then
        echo "ERROR: input empty..."
        exit 1
    fi
}

input_not_empty NAME "your full name"
input_not_empty EMAIL "your full email"

echo "name is $NAME"
echo "email is $EMAIL

but be careful with eval!

2 Comments

There are ways to do this without using eval.
Definitely without two uses of eval.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.