bash:strings:check_if_a_string_contains_a_substring
Table of Contents
BASH - Strings - Check if a String contains a Substring
Using double brackets with wildcard
string='My long string' if [[ $string == *"My long"* ]]; then echo "It's there!" fi
NOTE: Spaces in the Substring need to be placed between double quotes.
The * asterisks should be outside the double quotes.
A simple comparison operator is used (i.e. ==), not the regex operator =~.
The comparison can be reversed by just switching to != in the test.
Regex approach
string='My string'; if [[ $string =~ "My" ]]; then echo "It's there!" fi
Using a case statement
case "$string" in *foo*) # Do stuff ;; esac
bash/strings/check_if_a_string_contains_a_substring.txt · Last modified: 2021/01/11 11:21 by peter