How to check if a string contains a substring in Bash

后端 未结 26 2315
慢半拍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:27

    The accepted answer is best, but since there's more than one way to do it, here's another solution:

    if [ "$string" != "${string/foo/}" ]; then
        echo "It's there!"
    fi
    

    ${var/search/replace} is $var with the first instance of search replaced by replace, if it is found (it doesn't change $var). If you try to replace foo by nothing, and the string has changed, then obviously foo was found.

提交回复
热议问题