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

Bash检查字符串是否不包含其他字符串,bash,Bash,我在.sh脚本中有一个字符串${testmystring},我想检查这个字符串是否不包含其他字符串 if [[ ${testmystring} doesNotContain *"c0"* ]];then # testmystring does not contain c0 fi 我如何才能做到这一点,即不包含什么?使用= if [[ ${testmystring} != *"c0"* ]];then # testmystring does not co

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

    if [[ ${testmystring} doesNotContain *"c0"* ]];then
        # testmystring does not contain c0
    fi 
我如何才能做到这一点,即不包含什么?

使用
=

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

有关更多信息,请参阅
帮助[[

正如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

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

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"

{}
c0
周围的引号是多余的。我同意对于上面显示的示例来说,它们是多余的。但是如果变量名和模式字符串变得更复杂(例如:模式字符串中包含空格),引用它们是必要的。无论如何,引用它们通常没有坏处。:)没错,它没有坏处,如果你喜欢键入它们,那就把自己击倒!对不起,我知道这很迂腐,只是我发现人们经常死记硬背地使用像
{}
这样的东西,而不知道什么时候需要它们,什么时候不需要它们(我倒投了你一票)@cdarke:据我所知,没有使用{}会导致性能损失,因为shell不能立即假定它是一个变量,而它可以。我不能完全肯定,更糟糕的是,我记不起我在哪里看到了这些数字。@Randyman 99:虽然我同意你的目标,但我不相信在你不了解它们的作用时添加多余的字符会有好处编程实践。这是我的观点——太多人使用它们是因为一种货运文化,而他们从来没有了解它们的实际用途——这不是一种好的编程实践。防御性编程是好的,盲目编程是不好的。拿一个从事专业编程50年的人来说。
[[$testmystring!=*c0*]&&echo testmystring不包含c0
可能的重复项它是反向重复项:读取并使用
else
或与中不同:
if!string包含“c0”$myteststring;然后……
你用大炮杀死蚊子也许是对的,但是,如果有人执意采用这种方法,那么这一行就更简洁了:
如果echo$teststring | grep-q$anotherstring;那么echo“找到了”;否则echo“找不到”;fi