Bash如果在比较特定字符串

时间:2016-09-08 17:46:55

标签: linux bash shell

比较特定字符串

时条件不匹配的Bash

匹配字符串:

Red Hat Enterprise Linux Server release 7.2 (Maipo)

代码:

machineOSVersion="Red Hat Enterprise Linux Server release 7.2 (Maipo)"

modifiedOSVersion="CentOS Linux release 7 OR Red Hat Enterprise Linux Server release 7.2 (Maipo)"

if [[ ${machineOSVersion} = *"${modifiedOSVersion}"* ]]; then

    echo -e "match"

else

    echo -e "doesn't match"

fi

我希望这匹配,但事实并非如此。

相同的代码适用于其他字符串。这是因为字符串中的()字符而失败吗?

2 个答案:

答案 0 :(得分:3)

您在向后比较中得到了2个变量。您必须按如下方式编写条件:

if [[ ${modifiedOSVersion} = *"${machineOSVersion}"* ]]; then

您可以这样想:${modifiedOSVersion}是两个字符串中最大的一个,因此您需要向${machineOSVersion}添加内容以匹配它。这个附加内容由两个*表示。

答案 1 :(得分:2)

你有可变的匹配反转。您必须在子集变量周围使用*匹配而不是超集变量。

使用:

[[ $modifiedOSVersion == *"$machineOSVersion"* ]] && echo "matched" || echo "nope"
相关问题