Test if a string contains a substring

  • I have the code

    file="JetConst_reco_allconst_4j2t.png"
    if [[ $file == *_gen_* ]];
    then
        echo "True"
    else
        echo "False"
    fi
    

    I test if file contains "gen". The output is "False". Nice!

    The problem is when I substitute "gen" with a variable testseq:

    file="JetConst_reco_allconst_4j2t.png"
    testseq="gen"
    if [[ $file == *_$testseq_* ]];
    then
        echo "True"
    else
        echo "False"
    fi
    

    Now the output is "True". How could it be? How to fix the problem?

  • You need to interpolate the $testseq variable with one of the following ways:

    • $file == *_"$testseq"_* (here $testseq considered as a fixed string)

    • $file == *_${testseq}_* (here $testseq considered as a pattern).

    Or the _ immediately after the variable's name will be taken as part of the variable's name (it's a valid character in a variable name).

    Correct answer as it applies to OP, but w/o being portable. (This is no criticism of the provided answer, just a warning to readers). ;-)

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM