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

Go to top