4
Feb

Testing Input String for Numeric, Alpha-Numeric, Alpha, or Other POSIX

If you’re trying to scrub your input of a script, a good way to do it is using POSIX along with the tr -d command. This is demonstrated in the shell script below.

#!/bin/sh

# Any of the following can be used, only a few are
# demonstrated:
#[:alnum:]  # Alphanumeric characters
#[:alpha:]  # Alphabetic characters
#[:lower:]  # Lowercase letters
#[:upper:]  # Uppercase letters
#[:digit:]  # Decimal digits
#[:xdigit:] # Hexadecimal digits
#[:punct:]  # Punctuation
#[:blank:]  # Tabs and spaces
#[:space:]  # Whitespace characters
#[:cntrl:]  # Control characters
#[:print:]  # All printable characters
#[:graph:]  # All printable characters except for space
#[a-zA-Z0-9] # Same as [:alnum:]. POSIX can be used.


if [ $# -lt 1 ]; then
   echo "Usage: $0 <text>"
   exit
fi

text=$1

# Check that input is only numeric
if [ -z `echo $text | tr -d "[:digit:]"` ]; then
   echo "Input contains only numeric characters"
else
   echo "Error: input contains non-numeric characters"
fi

# Check that input is only alpha
if [ -z `echo $text | tr -d "[:alpha:]"` ]; then
   echo "Input contains alpha characters"
else
   echo "Error: input contains non-alpha characters"
fi

# Check that input is only alphanumeric
if [ -z `echo $text | tr -d "[:alnum:]"` ]; then
   echo "Input contains alphanumeric characters"
else
   echo "Error: input contains non-alphanumeric characters"
fi

Let’s give it a test run, shall we?

[email protected]$ ./input.sh text
Error: input contains non-numeric characters
Input contains alpha characters
Input contains alphanumeric characters
[email protected]$ ./input.sh text123
Error: input contains non-numeric characters
Error: input contains non-alpha characters
Input contains alphanumeric characters
[email protected]$ ./input.sh 123
Input contains only numeric characters
Error: input contains non-alpha characters
Input contains alphanumeric characters
[email protected]$ 

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 2 Comments So Far

  • Asia
    January 22nd, 2013 at 5:30 pm

    not working huhuhuhuhu

  • Yarillo
    November 25th, 2015 at 11:05 am

    #[a-zA-Z0-9] # Same as [:alnum:]. POSIX can be used.

    No. Please don’t do that. The world is bigger than ASCII. The french have letters like éèêôîï, the germans use a ß, all of this is taken care of by [alnum]. Use [alnum], it was made for a reason.

Share your thoughts, leave a comment!