Shell Programming Case Study #4
#!/bin/sh
# case study #4
# how to ask for user input until valid input is given.
# exit if too many wrong answers
LIMIT=7
CNT=0
while :
do
CNT=`expr $CNT + 1`
if [ $CNT -gt $LIMIT ]
then
break
fi
echo "\nEnter your full name: \c"
read NAME
if [ -z "$NAME" ]
then
echo "Error: missing input" >&2
continue
fi
CHECK=`echo "$NAME" | grep '.\{31\}'`
if [ -n "$CHECK" ]
then
echo "Error: name exceeds 30 characters" >&2
continue
fi
CHECK=`echo "$NAME" | grep '[^ ] [^ ]'`
if [ -z "$CHECK" ]
then
echo "Error: you must supply both first and last name" >&2
continue
fi
break
done
if [ $CNT -gt $LIMIT ]
then
echo "Error: too many invalid inputs. Program aborted." >&2
exit 15
fi
echo "Nice to meet you $NAME"