Bash Find Out IF a Variable Contains a Substring

See all Bash/Shell scripting related FAQ
How do I determine whether a variable called spath=”/srv/www/” contains a substring called “”? How can I check if a string contains a Substring in Bash scripting?

You can always find out if a string/word/variable contains another string/word in Linux or Unix shell scripting. For example find out if a word called tips exists in $var="Here are some tips for you". There are many ways to test if a string is a substring in bash. We can find if variable contains a substring in our shell scripts using awk, perl, bash, and other methods.
Tutorial requirements
RequirementsLinux/Unix with bash
Root privileges No
Difficulty level Easy
Est. reading time 2 minutes
How to find a string is a substring in bash

Find out if bash variable contains a substring

Let us see various bash methods to check if a string contains a substring.

Using case syntax

You can use the portable BourneShell syntax as follows:

case "$var" in
    *pattern1* ) echo "do something #1";;
    *pattern2* ) echo "do something # 2";;
    * ) echo "Error...";;

Here is a sample code:

	echo "Running rsync..."
        rsync -ar $spath/*$spath
# Checks if the value of spath contains the substring ""
# If it does, the sync_root function is invoked.
case "$spath" in
    **) sync_root ;;
    *) echo "Error: Domain does not exits in path.";;	

Bash check if a string contains a substring

The [ and [[ evaluate conditional expression. This is a synonym for the test command/builtin. However, [[ is bash’s improvement to the [ command. Please note that the following is bash specific syntax and it will not work with BourneShell:

[[ $var = *pattern1* ]]
## OR ##
if [[ $var = *pattern1* ]]
    echo "Do something"

Here is a sample code:

# Wrapper for faq pdf generator
# Manually generate pdf files and upload to static nixCraft download server
# --
# Get all defaults and functions 
[[ -f ~/backend/utils/ ]] && ~/backend/utils/
[[ $# -eq 0 ]] && { echo "Usage: $0 faq-url"; exit 1; }
[[ $1 != ** ]] && { printf "Error: Specify faq url (e.g.,\n"; exit 2; }
${_pdfwriter} faq "$1"

First define a shell variable in form of:


Now run bash for loop as follows using the ufw command:

for e in $_admin_ips
 # open port 22 to all IPs
 ufw allow from "${e%%|*}" to any port 22 proto tcp comment "Open TCP SSH PORT for ${e##*|}"
 # open port 80 and 443 only to our corporate IPs by matching them
 [[ "${e##*|}" =~ .*CORP_* ]] && { 
 		ufw allow from "${e%%|*}" to any port 443 proto tcp comment "Open HTTPS PORT for ${e##*|}";
 		ufw allow from "${e%%|*}" to any port 80 proto tcp comment "Open HTTP PORT for ${e##*|}";

Using bash regex syntax

Bash v3 and above also supports additional regular expressions. The syntax is as follows to see if bash variable contains a substring:

[[ $var =~ .*substring.* ]]
[[ $value =~ .*container1.* ]] && do_something

For example find out if a word ‘faq’ exists in $url:

[[ $url =~ .*faq* ]] && echo "Found" || echo "Not found"
## if syntax ##
if [[ $url =~ .*faq.* ]] 
   echo "I found a word faq in ${url}."
   echo "Sorry. Not found."

Using AWK regex syntax

The syntax is pretty simple:

# define a var at shell
var="This is a test"
# use awk 
awk '$0~/test/{print "A substring called test found"}' <<< $var

The grep command syntax

In this example I am going to use the grep to check if a string contains a substring in Bash script:

var="Hello world"
grep -q 'foo' <<< $var && echo "A substring called foo found" || echo "Not a substring"
grep -q 'world' <<< $var && echo "A substring called world found" || echo "Not a substring"

Let us try out the if command in our tiny shell script:

my_quote='Look for opportunities in every change in your life'
if grep -q "${search_word}" <<< "$my_quote"
  echo "I found '${search_word}' word in \$my_quote variable."
  echo "Sorry I cannot find '${search_word}' word in \$my_quote variable."

For example here is my LXD backup script that ignore containers from backup defined in the $ignore:

# Purpose - Basic shell script to backup required LXD containers under Linux
# Author - Vivek Gite {} under GPL version 2.0+ 
# --------------------------------------------------------------------------
## Get today's date ##
NOW=$(date +'%m-%d-%Y')
# NFS mounted backup or AWS efs 
# Define config and other paths 
# Containers to ignore from backup 
ignore="nginx-build-service docker-test-service mysqld-test-data php8-build-service www-testing"
[ ! -d "$DEST" ] && mkdir -p "$DEST"
## Dump LXD server config ##
lxd init --dump > "${LXD_CONF}"
## Dump all instances list ##
lxc list > "${LXD_INST_LIST}"
## Make sure we know LXD version too ##
snap list lxd > "${LXD_VER}"
## Backup all Instances
for i in $(lxc list -c n --format csv)
     # Ignore backup for this container if defined in $ignore
     grep -q $i <<< $ignore && continue	
     lxc export "${i}" "$file" --optimized-storage --compression xz


Checking if a variable contains a substring is useful in bash scripting. Of course, we can can use Perl, Python and more too. See your local bash man page for more information:
$ man bash
$ man grep
$ man awk

🥺 Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🤠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

10 comments… add one
  • yoander Mar 16, 2010 @ 13:58

    BASH Regular expression

    [[ $var =~ '.**' ]] && echo Yes || echo No

  • yoander Mar 16, 2010 @ 14:04

    BASH Regular expression

    [[ '/srv/www/' =~ '.**' ]] && echo Yes || No

  • yoander Mar 16, 2010 @ 14:06

    [[ '/srv/www/' =~ '.**' ]] && echo Yes || echo No

  • Santosh Nov 14, 2012 @ 14:05

    Thank you!

  • toto Feb 1, 2013 @ 22:08
    if [ "${haystack}" != "${haystack/${needle}/}" ]
      echo "found needle in haystack"
  • taikedz Jun 16, 2017 @ 18:05

    Wow plenty commenting on the bash regex. Well I just wanted to chime in there too. This is sufficient:

        [[ "$MYVAR" =~ ]] && echo "Yes it does."

    It should be noted that the pattern should NOT be quoted, else it is treated as a literal (yoander’s examples are, alas, incorrect)

    I frequently do an arguments check at the start of my scripts to see if we should just print help and exit:


    Edited by admin to correct syntax.

    • taikedz Jun 16, 2017 @ 18:06

      Of course, I forgot a ‘[‘ in my second example :-/

  • Nina Aug 2, 2020 @ 14:24

    How about?


  • Sai Aug 2, 2020 @ 16:33

    I had no idea about such a good bash syntax.

  • Trey Blancher Aug 2, 2020 @ 19:11

    You need to pick a better font for displaying monospace text. The tildes (`~`) look way too similar to hyphens/dashes (`-`), I had to increase the font size and still I had difficulty verifying those were indeed tildes.

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.