两个相等的字符串在bash中评估为不相等

时间:2014-04-16 14:54:19

标签: bash

代码:

DKIM_RECORD='v=DKIM1\;t=s\;n=core\;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr0WehGwX2nEq4WY3OmiGnYtRt2941lJBsoDMV485apTs4MagWxuzRCkil7/A9fV/FJdt+bzRcdgurcZBbrwI5PpfACUP4ghL9ZU8H9lwbWIGNu0hpqEE+0cdigB1S54B7Fj/AXx5hA9nBuNA27KD+hpBx4ToUIDhDFy9A6BodO6yHr/CkccGuZJO7dMPMWyycx+CTaJSB4fDQmwtPbYf9NHaucud0h902DIajfiJpZ4CEvCjNU8pcsAXecCBLqnWLkj2b7AxYpX+A4+z1GR5mul1IQQcfkspm1v/ihdWZ+FogtquMpos9u+6OSnXkQfYW83XED6hNE335kgoSDAWgQIDAQAB'
DKIM_RESPONSE=`dig @ns0.transip.net default._domainkey.randomdomain.nl TXT +short | tr -d '" ' `

if [[ $DKIM_RESPONSE != $DKIM_RECORD ]]; then
    echo "$DKIM_RESPONSE"
    echo "$DKIM_RECORD"
    echo "randomdomain.nl: DKIM failed"
fi

结果:

v=DKIM1\;t=s\;n=core\;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr0WehGwX2nEq4WY3OmiGnYtRt2941lJBsoDMV485apTs4MagWxuzRCkil7/A9fV/FJdt+bzRcdgurcZBbrwI5PpfACUP4ghL9ZU8H9lwbWIGNu0hpqEE+0cdigB1S54B7Fj/AXx5hA9nBuNA27KD+hpBx4ToUIDhDFy9A6BodO6yHr/CkccGuZJO7dMPMWyycx+CTaJSB4fDQmwtPbYf9NHaucud0h902DIajfiJpZ4CEvCjNU8pcsAXecCBLqnWLkj2b7AxYpX+A4+z1GR5mul1IQQcfkspm1v/ihdWZ+FogtquMpos9u+6OSnXkQfYW83XED6hNE335kgoSDAWgQIDAQAB
v=DKIM1\;t=s\;n=core\;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr0WehGwX2nEq4WY3OmiGnYtRt2941lJBsoDMV485apTs4MagWxuzRCkil7/A9fV/FJdt+bzRcdgurcZBbrwI5PpfACUP4ghL9ZU8H9lwbWIGNu0hpqEE+0cdigB1S54B7Fj/AXx5hA9nBuNA27KD+hpBx4ToUIDhDFy9A6BodO6yHr/CkccGuZJO7dMPMWyycx+CTaJSB4fDQmwtPbYf9NHaucud0h902DIajfiJpZ4CEvCjNU8pcsAXecCBLqnWLkj2b7AxYpX+A4+z1GR5mul1IQQcfkspm1v/ihdWZ+FogtquMpos9u+6OSnXkQfYW83XED6hNE335kgoSDAWgQIDAQAB
randomdomain.nl: DKIM failed

两个字符串看起来都相等,但bash评估为不等。这里出了什么问题?

1 个答案:

答案 0 :(得分:6)

如果未引用!=的右侧参数,则将其视为要匹配的模式,而不是要与之比较的文字字符串。 DKIM_RECORD包含反斜杠,因此当其扩展被解释为模式时,反斜杠用于转义后续字符,然后被删除。这意味着左侧的值不再与右侧的值匹配。一个较小的例子应该让它更清晰。

$ foo="x\;y"
$ bar="x\;y"
# Here, the value of foo is matched against the pattern "x;y"
$ [[ $foo != $bar ]] && echo no match
no match
# Here, the value of $foo is compared to the string "x\;y"
$ [[ $foo != "$bar" ]] && echo no match
$

你只需引用右手参数:

if [[ $DKIM_RESPONSE != "$DKIM_RECORD" ]]; then