Posts bash 判断字符串是否包含另一个字符串
Post
Cancel

bash 判断字符串是否包含另一个字符串

how to check if a string contains a substring in bash

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

1
2
3
4
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 =~.

If you prefer the regex approach:

1
2
3
4
5
string='My string';
if [[ $string =~ "My" ]]
then
   echo "It's there!"
fi
This post is licensed under CC BY 4.0 by the author.