mondragonfx
mondragonfx

Reputation: 87

Multiple Read statements. Do not proceed until user input is given

I have a few read statements. Im trying to figure out how to prevent the user from going to the next statement unless they have provided user input. I am having trouble wrapping my head around this. I have seen examples for a single read -p statement but can't seem to find an appropriate solution for multiple subsequent read statements.

     read -p " Write something: " var1
     read -p " Write something again: " var2
     read -p " write something a third time: " var3
 desired output
 Write something: #no input
 You have not entered anything. Please try again.
 Write something: computer
 Write something again

then proceed accordingly.

Upvotes: 0

Views: 62

Answers (2)

Ivan
Ivan

Reputation: 7277

Same as Cyrus posted but with a warning

until [[ "$var1" ]]; do
    read -p " Write something: " var1
    [[ "$var1" ]] || echo "You have not entered anything. Please try again."
done

And this will create all vars in one loop

vars=(var1 var2 var3)

for varname in ${vars[@]}; {
    until [[ "${!varname}" ]]; do
        read -p " Write something to $varname: " $varname
        [[ "${!varname}" ]] || echo "You have not entered anything. Please try again."
    done    
}

We can go further and use an array to store data

for i in {1..3}; {
    until [[ "${vars[$i]}" ]]; do
        read -p "Write something to var$i: " vars[$i]
        [[ "${vars[$i]}" ]] || echo "You have not entered anything. Please try again."
    done    
}

Upvotes: 0

Cyrus
Cyrus

Reputation: 88583

With bash:

while [[ "$var1" = "" ]]; do read -p " Write something: " var1; done

Upvotes: 1

Related Questions