Substring detection is a fundamental task in Bash scripting. Whether you're validating input, parsing logs, or controlling program logic, checking if a string contains a specific substring is a common requirement. This guide demonstrates multiple ways to perform substring checks in Bash using conditionals, pattern matching, regular expressions, and utility commands, following best practices for clarity and reliability. By the end, you'll have a working demo script that runs every substring-matching method back to back.

1. The Short Answer Version

Here's a quick summary of how to check for substrings using different Bash techniques:

# Pattern match using [[ and wildcard string="Welcome to Linux" if [[ $string == *"Linux"* ]]; then echo "Match found"; fi # Regex match using [[ and =~ if [[ $string =~ Linux ]]; then echo "Regex match"; fi # Grep match (exit status 0 = found) echo "$string" | grep -q "Linux" echo $? # Case statement match case $string in *"Linux"*) echo "Matched via case";; esac # expr index (returns >0 if found) expr index "$string" "Linux" 

Each method checks whether "Linux" is present in the $string. Continue below for full breakdowns and use cases.

2. Use [[ with * Pattern Matching

The simplest and most common way to check if a string contains a substring is by using the [[ conditional expression with the * wildcard.

Command Syntax

[[ $string == *substring* ]] 
  • [[ ... ]]: Bash test command
  • == *substring*: Matches any string containing substring

Command Demonstration

1. Define the string variable:

$ string="Welcome to Linux" 

2. Run the substring check using [[ ... == *substring* ]]:

$ if [[ $string == *"Linux"* ]]; then echo "Match found"; else echo "No match"; fi 

The [[ ... == *"Linux"* ]] expression uses * as a wildcard to match any text before or after "Linux". If $string contains "Linux", the condition evaluates to true (exit code 0), and echo "Match found" runs. Otherwise, the condition is false (exit code 1), and echo "No match" runs.

Output:

Match found 

This approach is reliable for basic substring checks in simple scripts or one-liners.

3. Use case Statement for Substring Match

The case statement is useful for matching substrings against multiple patterns. It's more readable than chaining if statements, especially when checking for several possible values.

Command Syntax

case $string in *substring*) commands ;; *) fallback ;; esac 
  • case $string in: Begins the pattern check
  • *substring* ): Wildcard match for the substring
  • ;;: Ends each matching block
  • esac: Terminates the case structure

Command Demonstration

1. Define the string:

$ string="Backup completed" 

2. Match against a substring using case:

$ case $string in *"completed"*) echo "Success detected" ;; *) echo "No success message" ;; esac 

The case statement compares $string against each pattern in order, from top to bottom. The pattern *"completed"* matches any string containing the substring "completed". When a match is found, the associated command (echo "Success detected") runs, and execution exits the case block without checking further patterns.

Output:

Success detected 

This method is ideal when you need to match against multiple possible substrings in a clean, structured way.

4. Use grep to Check Substring in a Variable

The grep command is useful for substring detection, especially when reading from input or working with piped data.

Command Syntax

echo "$string" | grep -q "substring" 
  • -q: Quiet mode, suppresses normal output
  • Exit status $?:
    • 0: match found
    • 1: no match

Command Demonstration

1. Define the string:

$ string="Welcome to Linux" 

2. Search for the substring using grep:

$ echo "$string" | grep -q "Linux" $ echo $? 

The -q option makes grep operate in quiet mode, suppressing normal output and only setting the exit status. An exit code of 0 means the substring "Linux" was found in the input, while 1 means no match was found.

Output:

0 

A return value of 0 indicates the substring was found. Use this method when you want to integrate substring checks with command pipelines or external input.

5. Use expr index to Find Substring Position

The expr index command returns the position of the first occurrence of any character in the search string. If the result is greater than 0, a match was found.

Command Syntax

expr index "$string" "substring" 
  • Returns the 1-based index of the first matching character.
  • Returns 0 if no character from the search string is found.

Command Demonstration

1. Define the string:

$ string="Welcome to Linux" 

2. Check the position of the substring:

$ expr index "$string" "L" 

The expr index command returns the 1-based position of the first occurrence of any character from the search string. In this case, "L". If the result is greater than 0, it means the character (and therefore the substring starting with it) exists in $string. A result of 0 means no match was found.

Output:

12 

This means the character L (the first character of "Linux") appears at position 12.

6. Use [[ with =~ for Regular Expression Matching

Bash supports regular expression matching using the =~ operator inside [[ ... ]]. This is useful when you need more flexible matching than basic wildcards allow.

Command Syntax

[[ $string =~ pattern ]] 
  • =~: Matches the given regular expression
  • Returns exit code 0 if matched, 1 otherwise

Command Demonstration

1. Define the string:

$ string="Deploy succeeded" 

2. Match using regex:

$ if [[ $string =~ succeeded ]]; then echo "Found"; fi 

The [[ $string =~ succeeded ]] expression checks if $string contains text matching the regex succeeded. If a match is found, the condition evaluates to true (exit code 0), and "Found" is printed. Otherwise, it evaluates to false (exit code 1), and nothing is printed.

Output:

Found 

This method is ideal for flexible substring matching or pattern recognition.

7. Create a Substring Demo Script

Follow these steps to test all substring matching methods in one script.

1. Create a new file for your script:

$ touch substring_demo.sh 

Or open it directly with a text editor:

$ nano substring_demo.sh 

2. Add the following content to the file:

#!/bin/bash text="System reboot scheduled" # Pattern match if [[ $text == *"reboot"* ]]; then echo "Using wildcard: 'reboot' found." fi # Regex match if [[ $text =~ reboot ]]; then echo "Using regex: 'reboot' found." fi # Grep method if echo "$text" | grep -q "reboot"; then echo "Using grep: 'reboot' found." fi # Case statement case $text in *"reboot"*) echo "Using case: 'reboot' found." ;; *) echo "Using case: Not found." ;; esac # expr index if [ "$(expr index "$text" reboot)" -ne 0 ]; then echo "Using expr: 'reboot' found." fi 

Save and close the file.

3. Make the script executable:

$ chmod +x substring_demo.sh 

4. Run the script:

$ ./substring_demo.sh 

Output:

Using wildcard: 'reboot' found. Using regex: 'reboot' found. Using grep: 'reboot' found. Using case: 'reboot' found. Using expr: 'reboot' found. 

8. Check if String is Non-empty Before Matching

Before performing a substring match, it's good practice to ensure the string is not empty. This prevents unexpected behavior in scripts that process dynamic input.

Command Syntax

[ -n "$string" ] 
  • -n "$string": Returns true if the string is non-empty

Command Demonstration

1. Define the string:

$ string="hello" 

2. Check if the string is non-empty:

$ [ -n "$string" ] && echo "Not empty" || echo "Empty string" 

The [ -n "$string" ] test returns true (exit code 0) if $string is non-empty and false (exit code 1) if it is empty. The && operator runs the next command only when the previous command succeeds, while || runs the next command only when the previous command fails.

Output:

Not empty 

This is especially helpful when working with user input, file reads, or optional arguments.

Next Steps

  • Combine substring checks with input validation to guard scripts against malformed arguments.
  • Use grep -q inside pipelines when scanning log files or command output for keywords.
  • Explore BASH_REMATCH to capture and reuse the parts of a string matched by =~.
  • Benchmark [[ ... ]] wildcard matching against grep for performance-sensitive, high-iteration scripts.

For the full guide with additional tips, visit the original article on Vultr Docs.