How to do "contains string" test in Bash?

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

asked Dec 16, 2015 by anonymous

1 Answer

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
answered Dec 17, 2015 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...