Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains a substring in Bash

I have a string in Bash:

string="My string" 

How can I test if it contains another string?

if [ $string ?? 'foo' ]; then   echo "It's there!" fi 

Where ?? is my unknown operator. Do I use echo and grep?

if echo "$string" | grep 'foo'; then   echo "It's there!" fi 

That looks a bit clumsy.

like image 346
davidsheldon Avatar asked Oct 23 '08 12:10

davidsheldon


People also ask

How do you check if a string contains a substring in Shell?

Using Regex Operator Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk .

How do you check if a string does not contains a substring in bash?

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


1 Answers

You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:

string='My long string' if [[ $string == *"My long"* ]]; then   echo "It's there!" fi 

Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside. Also note that a simple comparison operator is used (i.e. ==), not the regex operator =~.

like image 134
Adam Bellaire Avatar answered Sep 27 '22 00:09

Adam Bellaire