Bash String Comparison: Find Out IF a Variable Contains a Substring

How do I determine whether a variable called spath=”/srv/www/” contains a substring called “”?

You can always find out if a string/word 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.

Method 1: Use case sytnax

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.";;	

Method 2: Bash specific syntax

The following is bash specific syntax and it will not work with BourneShell:

[[ $var = *pattern1* ]]


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

Here is a sample code:

# Wrapper for faq pdf generator
# Manually generate pdf files and upload to static SXI LLC 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.,"; exit 2; }
${_pdfwriter} faq "$1"

Method 3: Bash regex syntax

Bash v3 and above also supports additional regular expressions. The syntax is:

[[ $var =~ .*substring.* ]]

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."

Method 4: 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

Method 5: grep syntax

The syntax is as follows:

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"

You can use perl, python and more. See your local bash man page for more information:
man bash
man grep
man awk

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Leave a Reply

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

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts