How to do “contains string” test in Bash?

How to test whether a string $str contains another string $needle in Bash?

You can use this piece of Bash script:

[[ "$str" == *"$needle"* ]]

A usage example:

$ str="abcde hello"
$ needle1="deh"
$ needle2="de hello"
$ [[ "$str" == *"$needle1"* ]] && echo "matched"
$ [[ "$str" == *"$needle2"* ]] && echo "matched"
matched

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *