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

by on March 16, 2010 · 5 comments· LAST UPDATED March 16, 2010

in

How do I determine whether a variable called spath="/srv/www/cyberciti.biz/https" contains a substring called "cyberciti.biz"?

You can use the portable BourneShell syntax as follows:

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

Here is a sample code:

#!/bin/bash
spath="/srv/www/cyberciti.biz/https"
sync_root(){
	echo "Running rsync..."
        rsync -ar $spath/* root@backup.cyberciti.biz:$spath
}
 
case "$spath" in
    *cyberciti.biz*) sync_root ;;
    *) echo "Error: Domain does not exits in path.";;
esac

Bash Specific Syntax

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

[[ $var = *pattern1* ]]

OR

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

Here is a sample code:

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

Bash v3 and above also supports additional regular expressions. See your local bash man page for more information:
man bash

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 5 comments… read them below or add one }

1 yoander March 16, 2010 at 1:58 pm

BASH Regular expression

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

Reply

2 yoander March 16, 2010 at 2:04 pm

BASH Regular expression

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

Reply

3 yoander March 16, 2010 at 2:06 pm

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

Reply

4 Santosh November 14, 2012 at 2:05 pm

Thank you!

Reply

5 toto February 1, 2013 at 10:08 pm

if [ "${haystack}" != "${haystack/${needle}/}" ]
then
echo “found needle in haystack”
fi

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , ,

Previous Faq:

Next Faq: