Wicked Cool Shell Scripts
Wicked Cool Shell Scripts :: shell script 002-validalnum.sh

Shell Script 002-validalnum.sh

#!/bin/sh
# validalAlphaNum - Ensures that input only consists of alphabetical
#              and numeric characters.

validAlphaNum()
{
  # validate arg: returns 0 if all upper+lower+digits, 1 otherwise

  # Remove all unacceptable chars
  compressed="$(echo $1 | sed -e 's/[^[:alnum:]]//g')"

  if [ "$compressed" != "$input" ] ; then
    return 1
  else
    return 0
  fi
}

# Sample usage of this function in a script

echo -n "Enter input: "
read input

if ! validAlphaNum "$input" ; then
  echo "Your input must consist of only letters and numbers." >&2
  exit 1
else
  echo "Input is valid."
fi

exit 0

Explore The Book!
[book cover]
Table of Contents
Read Some Scripts!
Shell Script Library
Book Errata
All The Links
Read the Reviews
Talk About It
Author Bio
Buy The Book!



Other books by author Dave Taylor
Learning Unix for Mac OS X (O'Reilly & Associates)
Solaris 9 for Dummies (Wiley)
Teach Yourself Unix in 24 Hours (Sams/Macmillan)
Teach Yourself Unix System Administration in 24 Hours (Sams/Macmillan)
Creating Cool HTML 4 Web Pages (Wiley)