Bash checking if string does not contain other string

Bash

Bash Problem Overview


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, i.e. what is doesNotContain supposed to be?

Bash Solutions


Solution 1 - Bash

Use !=.

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

See help [[ for more information.

Solution 2 - Bash

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"

Solution 3 - Bash

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmachineryView Question on Stackoverflow
Solution 1 - BashcychoiView Answer on Stackoverflow
Solution 2 - BashThiago ConradoView Answer on Stackoverflow
Solution 3 - BashRoberto De OliveiraView Answer on Stackoverflow