
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.
Here’s a quick summary of how to check for substrings using different Bash techniques:
Each method checks whether "Vultr" is present in the $string. Continue below for full breakdowns and use cases.
[[ with * Pattern MatchingThe simplest and most common way to check if a string contains a substring is by using the [[ conditional expression with the * wildcard.
[[ ... ]]: Bash test command== *substring*: Matches any string containing substringDefine the string variable.
Run the substring check using [[ ... == *substring* ]].
[[ ... == *"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:
This approach is reliable for basic substring checks in simple scripts or one-liners.
case Statement for Substring MatchThe 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.
case $string in: Begins the pattern check*substring* ): Wildcard match for the substring;;: Ends each matching blockesac: Terminates the case structureDefine the string.
Match against a substring using case.
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:
This method is ideal when you need to match against multiple possible substrings in a clean, structured way.
grep to Check Substring in a VariableThe grep command is useful for substring detection, especially when reading from input or working with piped data.
-q: Quiet mode, suppresses normal output$?:0: match found1: no matchDefine the string.
Search for the substring using grep.
-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:
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.
expr index to Find Substring PositionThe 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.
0 if no character from the search string is found.Define the string.
Check the position of the substring.
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:
This means the character V (the first character of "Vultr") appears at position 12.
[[ with =~ for Regular Expression MatchingBash supports regular expression matching using the =~ operator inside [[ ... ]]. This is useful when you need more flexible matching than basic wildcards allow.
=~: Matches the given regular expression0 if matched, 1 otherwiseDefine the string.
Match using regex.
[[ $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:
This method is ideal for flexible substring matching or pattern recognition.
Follow these steps to test all substring matching methods in one script:
Create a new file for your script.
Or open it directly with a text editor:
Add the following content to the file:
Save and close the file.
Make the script executable.
Run the script.
Output:
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.
-n "$string": Returns true if the string is non-emptyDefine the string.
Check if the string is non-empty.
[ -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:
This is especially helpful when working with user input, file reads, or optional arguments.
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.
0 Comments
Be the first to comment and share your perspective with the community.