Bash检查字符串是否包含其他字符串

时间:2015-05-31 12:36:37

标签: bash

我的 .sh 脚本中有一个字符串${testmystring},我想检查此字符串是否包含其他字符串。

    if [[ ${testmystring} doesNotContain *"c0"* ]];then
        # testmystring does not contain c0
    fi 

我怎么能这样做,即什么是notContain应该是什么?

3 个答案:

答案 0 :(得分:76)

使用!=

if [[ ${testmystring} != *"c0"* ]];then
    # testmystring does not contain c0
fi

有关详细信息,请参阅help [[

答案 1 :(得分:6)

正如mainframer所说,你可以使用grep,但我会使用退出状态进行测试,试试这个:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

答案 2 :(得分:3)

Bash允许u使用=〜测试是否包含子字符串。 因此,使用求反法可以测试相反的结果。

keystoreStoreFile = _________
keystoreStorePassword = ____________
keystoreKeyAlias = _______________
keystoreKeyPassword = ____________