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

我在我的.sh脚本中有一个字符串${testmystring} ,我想检查这个字符串是否不包含另一个字符串。

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

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


使用!=

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

请参阅help [[获取更多信息。


正如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/36201.html

上一篇: Bash checking if string does not contain other string

下一篇: Position of a string within a string using Linux shell script?