Image of the glider from the Game of Life by John Conway
Skip to content

Testing AlphaNumeric Arguments In Bash

Spending the evening working on my shell scripting, I thought I would jump into "Wicked Cool Shell Scripts" by Dave Taylor. In his script validalnum.sh, he has a test case to check if a user entered in valid alphabetic or numeric characters. His result is elegant and clean. I've changed up the script a bit for clarity:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash

echo -n "Enter alphanumeric input: "
read input

compressed="$(echo $input | sed -e 's/[^[:alnum:]]//g')"

if [ "$compressed" != "$input" ] ; then
    echo "Input not valid."
else
    echo "Input valid."
fi

In this example, the user is asked to enter input that can be any combination of letters and numbers, regardless of case. If the user enters punctuation, the test case fails, and the user is notified of such. Otherwise, the test case passes, and everyone is happy.

I want to call to your attention the cornerstone of this script, however:

1
compressed="$(echo $input | sed -e 's/[^[:alnum:]]//g')"

The variable $compressed is holding only alphanumeric characters. This is done by taking the user input, and piping it to the stream editor sed. With sed, we are searching for any character in the string that is not a number or a letter. If such a character exists, we remove the character altogether. Thus, if $compressed removes any characters, then it does not match what the user entered, and our test will fail. If no characters were removed, then no punctuation exists in the input, and our test case will pass.

I thought this was most clever, and just had to share, hoping others benefit from this simple example. I also hope that Dave is not mad at me for taking an example, changing it up a bit, and presenting it on this blog. Thanks Dave.

{ 10 } Comments