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

by Vivek Gite on March 16, 2010 · 3 comments

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

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 3 comments… read them below or add one }

1 yoander March 16, 2010

BASH Regular expression

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

Reply

2 yoander March 16, 2010

BASH Regular expression

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

Reply

3 yoander March 16, 2010

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

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 4 + 10 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the simple math so we know that you are a human and not a script.




Previous post:

Next post: