Bash Find Out IF a Variable Contains a Substring

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
Operating system/appLinux/Unix with bash
Root privileges requiredNo
DifficultyEasy (rss)
Estimated completion time2m
Table of contents
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
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"

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

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

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:

        if [[ "$*" =~ --help ]]; then
            printhelp ; 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?

    str='my string goes here'
    if [[ $str == *"string"* ]];
      echo "Found it"
      echo "Sorry"
  • 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.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.