Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check substring in Bourne Shell?

Tags:

sh

I wanna test whether a string has "substring". Most answers online is based on Bash. I tried

if [ $string == "*substring*" ] 

which was not working. Currently

if echo ${string} | grep -q "substring" 

worked. Is there any other better way.

like image 795
nathan Avatar asked Dec 14 '22 02:12

nathan


1 Answers

Using POSIX compliant parameter-expansion and with the classic test-command.

#!/bin/sh

substring=ab
string=abc

if [ "$string" != "${string%"$substring"*}" ]; then
    echo "$substring present in $string"
fi

(or) explicitly using the test operator as

if test "$string" != "${string%$substring*}" ; then
like image 129
Inian Avatar answered Apr 09 '23 21:04

Inian