标题就是全部内容。
另一种表述问题的方式是:在BASH中,检查一个字符串是否为由40(或32)个字符组成的序列,并且这些字符位于[0-9]
和[a-f]
范围内,有没有简洁的方法?
尝试以下内容,长度为32个字符:
if [[ $SOME_MD5 =~ ^[a-f0-9]{32}$ ]]
then
echo "Match"
else
echo "No match"
fi
使用函数:
is_valid() {
case $1 in
( *[!0-9A-Fa-f]* | "" ) return 1 ;;
( * )
case ${#1} in
( 32 | 40 ) return 0 ;;
( * ) return 1 ;;
esac
esac
}
[![:xdigit:]]
代替[!0-9A-Fa-f]
。sh
兼容(除了 case
中开括号我不太确定)。 - tripleee[!0-9a-f]
而不是 [^0-9a-f]
。而且你可能还想包括大写字母(原文如此)。 - tripleeestringZ=0123456789ABCDEF0123456789ABCDEF01234567
echo ${#stringZ}
40
echo `expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}'`
40
然后,测试${#stringZ}
是否等于expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}'
,如果字符串是32或40个字符且仅包含十六进制数字,则应为真。
就像这样:
#!/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
输出:
[ 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 ~ ]$
^[a-f0-9]{32}$
。 - elboulangero