Cybersecurity Updates & Tools

How To Check If A String Contains A Substring In Bash

Introduction

Checking whether a string contains a substring is a common task in Bash scripting. A string is a group of characters, and a substring is a smaller part of that string. For example, in the string kalilinuxtutorials.com, the word linux is a substring.

This is useful when writing Bash scripts for log analysis, file checking, user input validation, cybersecurity automation, and system monitoring. For example, you may want to check if a log line contains the word Failed, if a URL contains https, or if a filename contains .txt.

Using Double Brackets To Check Substring

The easiest way to check if a string contains a substring in Bash is by using double brackets [[ ]] with wildcard *.

Example:

#!/bin/bashtext="Welcome to Kali Linux Tutorials"if [[ "$text" == *"Linux"* ]]; then    echo "Substring found"else    echo "Substring not found"fi

Output:

Substring found

In this example, Bash checks whether the word Linux exists inside the variable text.

Basic Syntax

The basic syntax is:

if [[ "$string" == *"$substring"* ]]; then    echo "Found"else    echo "Not found"fi

The * symbols act as wildcards. They mean that any text can appear before or after the substring.

Check User Input For Substring

You can also check a substring from user input.

#!/bin/bashread -p "Enter a website URL: " urlif [[ "$url" == *"https"* ]]; then    echo "The website uses HTTPS"else    echo "The website may not use HTTPS"fi

This script asks the user to enter a URL and checks whether it contains https.

Check File Name Contains Extension

Substring checking is also useful when working with file names.

#!/bin/bashfile="report.txt"if [[ "$file" == *".txt"* ]]; then    echo "This is a text file"else    echo "This is not a text file"fi

This script checks whether the filename contains .txt.

Case-Sensitive Substring Check

By default, Bash substring matching is case-sensitive.

Example:

#!/bin/bashtext="Linux Security"if [[ "$text" == *"linux"* ]]; then    echo "Found"else    echo "Not found"fi

Output:

Not found

Here, Linux and linux are treated differently.

Case-Insensitive Substring Check

To perform a case-insensitive check, convert the string to lowercase:

#!/bin/bashtext="Linux Security"substring="linux"if [[ "${text,,}" == *"${substring,,}"* ]]; then    echo "Substring found"else    echo "Substring not found"fi

The ${text,,} syntax converts the text to lowercase.

Conclusion

Checking if a string contains a substring in Bash is simple and useful. The best method is to use [[ "$string" == *"$substring"* ]]. This method is easy to read and works well in most Bash scripts.

This technique is important for beginners because it helps in input validation, log filtering, file handling, and cybersecurity scripting. Once you understand substring checking, you can write smarter Bash scripts that make decisions based on text patterns.