I have one string and I want to check if it contains the sub-string or not. So I am using this command. Below is the Linux shell script. I just want to know how the condition present in if statement works?

STRING1='This string contains substring.'
if [[ $STRING1 != "${STRING1/substr/}" ]]; then
  echo "Substring is present"

That's a convoluted and ksh-specific (though now supported by a few other shells) way to write the standard:

case $STRING1 in
   *substr*) echo Substring is present

Or ksh-specific:

if [[ $STRING1 = *substr* ]]; then
  echo Substring is present

${var/pattern/replacement} is a ksh parameter expansion operator that expands to the value of $var where the first occurrence of pattern has been replaced with replacement.

So ${STRING1/substr/} is $STRING1 with the first occurrence of substr replaced with nothing, so removed.

[[ string = pattern ]] and [[ string != pattern ]] are another ksh specific construct that matches string against a pattern. When the pattern is quoted, it is taken literally, so [[ string = "string" ]] is an equality operator (and inequality with !=).

So the [[ $STRING1 != "${STRING1/substr/}" ]] command returns true if the expansion of $STRING1 and ${STRING!/substr/} yield different strings, which can only happen if there was at least one occurrence of substr within $STRING1, so it's a way to check that $STRING1 contains substr.

While neither [[...]] nor ${var/pattern/replacement} are standard sh syntax, the [ command and the ${var#pattern} operator (that latter one also coming from ksh) are standard. So you sometimes see code like:

if [ "$STRING1" != "${STRING1#*substr*}" ]; then
  echo Substring is present

Which is a standard (though not Bourne) way to check that a variable contains a substring, but again is convoluted and has no advantage over the obvious case statement approach.


check if it contains the sub-string

Seems simpler to execute

[ -z "${s##*substr*}" ] && echo Substring is present

The result of the expansion ${…} is null (zero length) if the substr is present.

... how the condition present in if statement works? The

if [[ $STRING1 != "${STRING1/substr/}" ]]; then

Is comparing two strings, the original unmodified and the same string with substr removed (/substr/}). If they are different (!=), the original string contained substr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.