Bash checking if string does not contain other string

I have a string ${testmystring} in my .sh script and I want to check if this string does not contain another string.

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

How can I do that, ie what is doesNotContain supposed to be?


Use != .

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

See help [[ for more information.


正如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
链接地址: http://www.djcxy.com/p/36202.html

上一篇: 字符串与通配符比较

下一篇: Bash检查字符串是否不包含其他字符串