It's all in the title.
An alternative way to phase the problem is: in BASH, what is a concise way of checking whether a string is a sequence of 40 (or 32) characters in the ranges [0-9]
and [a-f]
?
With a function:
is_valid() {
case $1 in
( *[!0-9A-Fa-f]* | "" ) return 1 ;;
( * )
case ${#1} in
( 32 | 40 ) return 0 ;;
( * ) return 1 ;;
esac
esac
}
If the shell supports POSIX character classes [![:xdigit:]]
could be used instead of [!0-9A-Fa-f]
.
Try this for 32 characters:
if [[ $SOME_MD5 =~ ^[a-f0-9]{32}$ ]]
then
echo "Match"
else
echo "No match"
fi
stringZ=0123456789ABCDEF0123456789ABCDEF01234567
echo ${#stringZ}
40
echo `expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}'`
40
Then, test if ${#stringZ}
equals expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}'
and it should be true if the string is 32 or 40 characters and only hexadecimal digits.
Like so:
#!/bin/bash
stringZ=""
while [ "$stringZ" != "q" ]; do
echo "Enter a 32 or 40 digit hexadecimal ('q' to quit): "
read stringZ
if [ "$stringZ" != "q" ]; then
if [ -n $stringZ ] && [ `expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}'` -eq ${#stringZ} ]; then
echo "GOOD HASH"
else
echo "BAD HASH"
fi
fi
done
Output:
[ 07:45 jon@host ~ ]$ ./hexTest.sh
Enter a 32 or 40 digit hexadecimal ('q' to quit):
1234567890abcdef1234567890abcdef
GOOD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
1234567890abcdef1234567890abcdef01234567
GOOD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
1234567890abcdef1234567890abcdef0
BAD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
123
BAD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
abcdef
BAD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
0123456789ABCDEF0123456789aBcDeF98765432
GOOD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
q
[ 07:46 jon@host ~ ]$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With