read command

Is there a way to use the READ command and force the user to enter a non-zero length string? If the user enters a zero length string the user input is rejected.

code:

print "what is the answer: \n"
read answer

Hi djehresmann:

while ! [ "$answer" ]; do read answer; done

or

while [ -z "$answer" ]; do read answer; done

Obviously, answer needs to be unset or empty when entering the while loop. Less obviously, assuming a default IFS value, leading whitespace will be discarded, so if whitespace alone is considered valid, you will want to set IFS to the null string (IFS='' read answer).

Regards,
Alister

With bash:

unset REPLY
until [[ $REPLY ]]; do read -p'Enter an answer: ';done