Search code examples
regexshellshposix

How to test if string matches a regex in POSIX shell? (not bash)


I'm using Ubuntu system shell, not bash, and I found the regular way can not work:

#!/bin/sh
string='My string';

if [[ $string =~ .*My.* ]]
then
   echo "It's there!"
fi

error [[: not found!

What can I do to solve this problem?


Solution

  • The [[ ... ]] are a bash-ism. You can make your test shell-agnostic by just using grep with a normal if:

    if echo "$string" | grep -q "My"; then
        echo "It's there!"
    fi