How to check if a string contains a substring in Bash

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

    The generic needle haystack example is following with variables

    #!/bin/bash
    
    needle="a_needle"
    haystack="a_needle another_needle a_third_needle"
    if [[ $haystack == *"$needle"* ]]; then
        echo "needle found"
    else
        echo "needle NOT found"
    fi
    

提交回复
热议问题