How to check if a string contains a substring in Bash

后端 未结 26 1923
慢半拍i
慢半拍i 2020-11-22 01:58

I have a string in Bash:

string=\"My string\"

How can I test if it contains another string?

if [ $string ?? \'foo\' ]; then         


        
26条回答
  •  再見小時候
    2020-11-22 02:14

    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 =~.

提交回复
热议问题