---
title: How to Check for a Substring in Bash
url: https://docs.vultr.com/how-to-check-for-a-substring-in-bash
description: Learn multiple methods to check for a substring in Bash scripts, including string operators, pattern matching, grep, and regular expressions for effective text processing.
publish_date: 2025-08-14T15:44:33.395862Z
last_updated: 2026-11-26T23:50:42.078938Z
author: Abhi Jindal
header_image: https://assets.vultrdevrel.com/docs-main-doc-assets-1/2286/49cd5ffd-7c42-4591-a9f0-11aade86ce4e.png
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

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 article 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.

## 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 Vultr"
    if [[ $string == *"Vultr"* ]]; then echo "Match found"; fi

# Regex match using [[ and =~

    if [[ $string =~ Vultr ]]; then echo "Regex match"; fi

# Grep match (exit status 0 = found)

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

# Case statement match

    case $string in *"Vultr"*) echo "Matched via case";; esac

# expr index (returns >0 if found)

    expr index "$string" "Vultr"
```

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

## 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.

    ```console
    $ string="Welcome to Vultr"
    ```

1. Run the substring check using `[[ ... == *substring* ]]`.

    ```console
    $ if [[ $string == *"Vultr"* ]]; then echo "Match found"; else echo "No match"; fi
    ```
    
    * The `[[ ... == *"Vultr"* ]]` expression uses `*` as a wildcard to match any text before or after `"Vultr"`. If `$string` contains `"Vultr"`, 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.

## 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.

    ```console
    $ string="Backup completed"
    ```

1. Match against a substring using `case`.

    ```console
    $ 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.

## 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.

    ```console
    $ string="Welcome to Vultr"
    ```

1. Search for the substring using `grep`.

    ```console
    $ echo "$string" | grep -q "Vultr"
    $ 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 `"Vultr"` 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.

## 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.

    ```console
    $ string="Welcome to Vultr"
    ```

1. Check the position of the substring.

    ```console
    $ expr index "$string" "V"
    ```

    * The `expr index` command returns the 1-based position of the first occurrence of any character from the search string. In this case, `"V"`. 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 `V` (the first character of "Vultr") appears at position 12.

## 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.

    ```console
    $ string="Deploy succeeded"
    ```

1. Match using regex.

    ```console
    $ 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.

## 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.

    ```console
    $ touch substring_demo.sh
    ```

    Or open it directly with a text editor:

    ```console
    $ nano substring_demo.sh
    ```

1. Add the following content to the file:

    ```bash
    #!/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.

1. Make the script executable.

    ```console
    $ chmod +x substring_demo.sh
    ```

1. Run the script.

    ```console
    $ ./substring_demo.sh
    ```

    Output:

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

## 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.

    ```console
    $ string="hello"
    ```

1. Check if the string is non-empty.

    ```console
    $ [ -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.

## Conclusion

In this article, you learned how to check for substrings in Bash using a variety of methods, including pattern matching, regular expressions, command-line utilities, and structured conditionals. Each approach serves different use cases, from quick checks in one-liners to robust logic in full scripts.

Mastering these techniques helps you write more reliable and maintainable Bash scripts for automation, input validation, log parsing, and beyond.
