Simple way to validate US postal codes using regular expression and optionally bash. US postall codes accept five digit ZIP number + optional 4 digit code. For example 32344-4444 and 32344 are valid codes but 323445-44 and 323445 are invalid.

#!/bin/bash

# regexp to get a valid US postal code
echo $1 | grep -qE '^[0-9]{5}(-[0-9]{4})?$' 

if [ $? -eq 0 ]; then
	echo "$1 is a valid US postal code."
else
	echo "$1 is an invalid US postal code."
fi

Execution:

$ chmod +x validate_us_postal_code.sh

$ ./validate_us_postal_code.sh 32344-4444
32344-4444 is a valid US postal code.

$ ./validate_us_postal_code.sh 32344
32344 is a valid US postal code.

$ ./validate_us_postal_code.sh 323445-44
323445-44 is an invalid US postal code.

$ ./validate_us_postal_code.sh 323445
323445 is an invalid US postal code.

Free Linux eBooks

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Linux Online Training

Learn to run Linux servers and prepare for LPI certification with Linux Academy. 104 available video lessons with PDF course notes with your own server!

Go to top