Linux /bin/sh check if string contains X

linux, shell

Solution

You can use a case statement:

case "$myvar" in
*string*) echo yes ;;
*       ) echo no ;;
esac

All you have to do is substitute `string` for whatever you need.

For example:

case "HELLOHELLOHELLO" in
*HELLO* ) echo "Greetings!" ;;
esac

Or, to put it another way:

string="HELLOHELLOHELLO"
word="HELLO"
case "$string" in
*$word*) echo "Match!" ;;
*      ) echo "No match" ;;
esac

Of course, you must be aware that `$word` should not contain magic glob characters unless you intend glob matching.

Problem

In a shell script, how can I find out if a string is contained within another string. In bash, I would just use =~, but I am not sure how I can do the same in /bin/sh. Is it possible?

Original source

Related problems