bash substring - How to check if a string contains a substring in Bash

bash check if string contains letters / string / bash / shell / substring / sh

I have a string in Bash:

string="My string"

How can I test if it contains another string?

if [ $string ?? 'foo' ]; then
  echo "It's there!"
if echo "$string" | grep 'foo'; then
  echo "It's there!"

Andrzej Sydor

Answer #1

Just do:

if grep -q foo <<<"$string"; then
    echo "It's there"
## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then

## Simply do this
if file -b "$1" | grep -q "tar archive"; then