Saturday 21 September 2024

How to Check if a String Contains a Substring in Bash

When it comes to string manipulation in Bash, checking if a string contains a specific substring is a common requirement. In this post, we’ll explore various methods to achieve this, ranging from simple conditional checks to more advanced techniques.

Using Conditional Expressions

The simplest way to check if a string contains a substring is by using conditional expressions. Here’s how you can do it:

string="My string"
substring="foo"

if [[ $string == *"$substring"* ]]; then
    echo "It's there!"
else
    echo "Not found."
fi
Read more »

Labels: