Languages
[Edit]
EN

Bash - check if string contains substring

3 points
Created by:
Zeeshan-Peel
850

In this article, we would like to show you how to check if string contains substring in Bash.

1. Using Wildcards

The simplest way to check if a string contains given substring is by using Bash wildcards.

#!/bin/bash

string='Example text...'
substring='text'

if [[ "$string" == *"$substring"* ]]; then
    echo "The string contains the substring."
fi

Run in command line:

./script.sh

Output:

The string contains the substring.

2. Using Regex

Another simple solution is to use regex operator (=~).

#!/bin/bash

string='Example text...'
substring='text'

if [[ "$string" =~ .*"$substring".* ]]; then
    echo "The string contains the substring."
fi

Run in command line:

./script.sh

Output:

The string contains the substring.
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join