
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 containingsubstring
Command Demonstration
Define the string variable.
console$ string="Welcome to Vultr"
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 totrue
(exit code0
), andecho "Match found"
runs. Otherwise, the condition isfalse
(exit code1
), andecho "No match"
runs.
Output:
Match found
This approach is reliable for basic substring checks in simple scripts or one-liners.
- The
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 blockesac
: Terminates thecase
structure
Command Demonstration
Define the string.
console$ string="Backup completed"
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 thecase
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.
- The
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 found1
: no match
Command Demonstration
Define the string.
console$ string="Welcome to Vultr"
Search for the substring using
grep
.console$ echo "$string" | grep -q "Vultr" $ echo $?
- The
-q
option makesgrep
operate in quiet mode, suppressing normal output and only setting the exit status. An exit code of0
means the substring"Vultr"
was found in the input, while1
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.- The
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
Define the string.
console$ string="Welcome to Vultr"
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 than0
, it means the character (and therefore the substring starting with it) exists in$string
. A result of0
means no match was found.
Output:
12
This means the character
V
(the first character of "Vultr") appears at position 12.- The
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
Define the string.
console$ string="Deploy succeeded"
Match using regex.
console$ if [[ $string =~ succeeded ]]; then echo "Found"; fi
- The
[[ $string =~ succeeded ]]
expression checks if$string
contains text matching the regexsucceeded
. If a match is found, the condition evaluates totrue
(exit code0
), and"Found"
is printed. Otherwise, it evaluates tofalse
(exit code1
), and nothing is printed.
Output:
Found
This method is ideal for flexible substring matching or pattern recognition.
- The
Create a Substring Demo Script
Follow these steps to test all substring matching methods in one script:
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
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.
Make the script executable.
console$ chmod +x substring_demo.sh
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
Define the string.
console$ string="hello"
Check if the string is non-empty.
console$ [ -n "$string" ] && echo "Not empty" || echo "Empty string"
- The
[ -n "$string" ]
test returnstrue
(exit code0
) if$string
is non-empty andfalse
(exit code1
) 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.
- The
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.
No comments yet.