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

por | 13 agosto, 2013

http://www.cyberciti.biz/faq/bash-find-out-if-variable-contains-substring/

 

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/* [email protected]:$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