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

Linux Technical Writer

LinuxCareer, Casual, Volunteer, Home Based

Do you wish to join Linuxcareer.com project and find out how to be a technical writer? We are now looking for volunteers to help us write tutorials and share them with Linux community

  • Casual work from home
  • 10 articles / year

Any active Linuxcareer.com’s author will be entitled to following benefits:

  • actively participate in Linuxcareer.com’s decision making process
  • feedback and help

APPLY

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