How to check if a string contains a substring in Bash

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

    You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an if with a [ or a [[. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use grep, and not the [ command.

    Just do:

    if grep -q foo <<<"$string"; then
        echo "It's there"
    fi
    

    Now that you are thinking of if as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?

    ## Instead of this
    filetype="$(file -b "$1")"
    if grep -q "tar archive" <<<"$filetype"; then
    #...
    
    ## Simply do this
    if file -b "$1" | grep -q "tar archive"; then
    #...
    

    The -q option makes grep not output anything, as we only want the return code. <<< makes the shell expand the next word and use it as the input to the command, a one-line version of the << here document (I'm not sure whether this is standard or a Bashism).

提交回复
热议问题