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.


Go to top