how to Find a substring in a bash shell script variable

LIST="some string with a substring you want to match"
SOURCE="substring"

if echo "$LIST" | grep -q "$SOURCE"; then
    echo "matched";
else
    echo "no match";
fi

Good Luck ;)


here is a correct construction of your if statement

if [[ "$variable" =~ "not found" ]]; then
      echo "Not Found";
else
      echo "Its there";
fi

Compare this with your version at the indicated points:

variable="This script is not found"  # <--

if [[ "$variable" =~ "not found" ]]  # <--
then
    echo "Not Found"
else
    echo "Its there"
fi  # <--

You can't put spaces around = in an assignment, and you need to quote a string literal that has spaces. You don't need a trailing ; if you're going to put then on its own line. And an if-then ends with "fi" not "if".

Tags:

Shell

Bash