Credit card numbers contain four groups of numbers where each group contains 4 numbers. The following regular expression ( regexp ) will accept all credit card number in this format: - 1234 5678 1234 5678 - 1234567812345678 - 1234-5678-1234-5678

#!/bin/bash

# regexp to get a valid credit card number

echo $1 | grep -qE '^([0-9]{4}[- ]?){3}[0-9]{4}$' 

if [ $? -eq 0 ]; then
	echo "$1 is a valid credit card number."
else
	echo "$1 is an invalid credit card number."
fi

Execution:

$ chmod +x validate_credit_card_number.sh

$ ./validate_credit_card_number.sh "1234 5678 1234 5678"
1234 5678 1234 5678 is a valid credit card number.

$ ./validate_credit_card_number.sh 1234567812345678
1234567812345678 is a valid credit card number.

$ ./validate_credit_card_number.sh 1234-5678-1234-5678
1234-5678-1234-5678 is a valid credit card number.

$ ./validate_credit_card_number.sh 1234-5678-1234-56786
1234-5678-1234-56786 is an invalid credit card number.

$ ./validate_credit_card_number.sh 1234-55678-1234-5678
1234-55678-1234-5678 is an invalid credit card number.



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