It's generally cleaner and more efficient to use a
case statement instead in this kind of situation. Also, you might consider using a
character class to eliminate all non-alphanumeric characters (or else build your own list of illegal characters inside the bracket expression). Wrapping the prompt in a
while+true loop ensures that it will keep asking until you get a legal name.
Code:
while true; do
read -r -p "Please enter your first name: " firstname
case $firstname in
*[^[:alnum:]]*) echo "Name contains illegal characters."
echo "Please try again."
continue
;;
*) echo "First name accepted: $firstname"
break
;;
esac
done
# do the same for the last name...
Also, when using
bash or
ksh, it's recommended to use
[[..]] for string/file tests, and
((..)) for numerical tests. Avoid using the old
[..] test unless you specifically need POSIX-style portability.
http://mywiki.wooledge.org/ArithmeticExpression
http://mywiki.wooledge.org/BashFAQ/031
http://wiki.bash-hackers.org/commands/classictest
http://wiki.bash-hackers.org/syntax/...nal_expression
(I'm specifically referring to your "
while [ $entername -le 1 ]" line here.)
Speaking of which, the bash/ksh "
[[" extended test can also do complex globbing and regex matches, but note that any special patterns on the right-hand-side need to remain unquoted.
Finally, please note that you were asked to use ***
[code][/code] tags*** around your code and data, which preserves formatting and improves readability. Please do
not use quote tags, colors, bolding, or other fancy formatting.