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"

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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