如果字符串不包含其他字符串,则执行 Bash 检查

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

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

我该怎么做,也就是说 NotContain 应该是什么?

166918 次浏览

Use !=.

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

See help [[ for more information.

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/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

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"