How to check if a string contains a substring in Bash

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

    As Paul mentioned in his performance comparison:

    if echo "abcdefg" | grep -q "bcdef"; then
        echo "String contains is true."
    else
        echo "String contains is not true."
    fi
    

    This is POSIX compliant like the 'case "$string" in' the answer provided by Marcus, but it is slightly easier to read than the case statement answer. Also note that this will be much much slower than using a case statement. As Paul pointed out, don't use it in a loop.

提交回复
热议问题