By davidsheldon


2008-10-23 12:37:31 8 Comments

I have a string in Bash:

string="My string"

How can I test if it contains another string?

if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi

Where ?? is my unknown operator. Do I use echo and grep?

if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi

That looks a bit clumsy.

24 comments

@BobMonk 2020-02-13 00:22:58

msg="message"

function check {
    echo $msg | egrep [abc] 1> /dev/null

    if [ $? -ne 1 ];
    then 
        echo "found" 
    else 
        echo "not found" 
    fi
}

check

This will find any occurance of a or b or c

@FifthAxiom 2019-12-04 15:14:29

Since the POSIX/BusyBox question is closed without providing the right answer (IMHO), I'll post an answer here.

The shortest possible answer is:

[ ${_string_##*$_substring_*} ] || echo Substring found!

or

[ "${_string_##*$_substring_*}" ] || echo 'Substring found!'

Note that the double hash is obligatory with some shells (ash). Above will evaluate [ stringvalue ] when the substring is not found. It returns no error. When the substring is found the result is empty and it evaluates [ ]. This will throw error code 1 since the string is completely substituted (due to *).

The shortest more common syntax:

[ -z "${_string_##*$_substring_*}" ] && echo 'Substring found!'

or

[ -n "${_string_##*$_substring_*}" ] || echo 'Substring found!'

Another one:

[ "${_string_##$_substring_}" != "$_string_" ] && echo 'Substring found!'

or

[ "${_string_##$_substring_}" = "$_string_" ] || echo 'Substring found!'

Note the single equal sign!

@Alex Skrypnyk 2019-02-02 06:03:56

Extension of the question answered here How do you tell if a string contains another string in POSIX sh?:

This solution works with special characters:

# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"

    if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"

contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"

contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"

@joeytwiddle 2019-12-12 10:34:38

The test contains "-n" "n" doesn't work here, because echo -n will swallow the -n as an option! A popular fix for that is to use printf "%s\n" "$string" instead.

@dengApro 2020-01-23 12:25:31

perfectly , solved string contained spaces

@Mike Q 2018-10-05 18:54:36

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash, IMO.

Here are some examples Bash 4+:

Example 1, check for 'yes' in string (case insensitive):

    if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

     if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

     if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

     if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

     if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

     if [ "$a" = "$b" ] ;then

Example 8, wildcard match .ext (case insensitive):

     if echo "$a" | egrep -iq "\.(mp[3-4]|txt|css|jpg|png)" ; then

Enjoy.

@Leslie Satenstein 2017-01-14 05:36:44

My .bash_profile file and how I used grep:

If the PATH environment variable includes my two bin directories, don't append them,

# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

U=~/.local.bin:~/bin

if ! echo "$PATH" | grep -q "home"; then
    export PATH=$PATH:${U}
fi

@codeforester 2017-01-14 06:01:17

Is this an answer?

@Mohamed Bana 2017-02-07 13:37:55

upvote. why bother to learn how Bash does it when grep, far more powerful, is more than likely going to be available. also extend it a bit further by matching against a list of patterns: grep -q -E 'pattern1|...|patternN'.

@Samuel 2014-12-31 22:32:14

As Paul mentioned in his performance comparison:

if echo "abcdefg" | grep -q "bcdef"; then
    echo "String contains is true."
else
    echo "String contains is not true."
fi

This is POSIX compliant like the 'case "$string" in' the answer provided by Marcus, but it is slightly easier to read than the case statement answer. Also note that this will be much much slower than using a case statement. As Paul pointed out, don't use it in a loop.

@Paul Hedderly 2014-08-27 19:42:38

So there are lots of useful solutions to the question - but which is fastest / uses the fewest resources?

Repeated tests using this frame:

/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do TEST ; x=$(($x-1)); done'

Replacing TEST each time:

[[ $b =~ $a ]]           2.92 user 0.06 system 0:02.99 elapsed 99% CPU

[ "${b/$a//}" = "$b" ]   3.16 user 0.07 system 0:03.25 elapsed 99% CPU

[[ $b == *$a* ]]         1.85 user 0.04 system 0:01.90 elapsed 99% CPU

case $b in *$a):;;esac   1.80 user 0.02 system 0:01.83 elapsed 99% CPU

doContain $a $b          4.27 user 0.11 system 0:04.41 elapsed 99%CPU

(doContain was in F. Houri's answer)

And for giggles:

echo $b|grep -q $a       12.68 user 30.86 system 3:42.40 elapsed 19% CPU !ouch!

So the simple substitution option predictably wins whether in an extended test or a case. The case is portable.

Piping out to 100000 greps is predictably painful! The old rule about using external utilities without need holds true.

@Mad Physicist 2016-07-13 16:28:20

Neat benchmark. Convinced me to use [[ $b == *$a* ]].

@tripleee 2018-04-12 06:59:08

If I'm reading this correctly, case wins with the smallest overall time consumption. You are missing an asterisk after $b in *$a though. I get slightly faster results for [[ $b == *$a* ]] than for case with the bug corrected, but it could depend on other factors too, of course.

@tripleee 2018-04-12 08:41:58

ideone.com/5roEVt has my experiment with some additional bugs fixed and tests for a different scenario (where the string is actually not present in the longer string). Results are largely similar; [[ $b == *$a* ]] is quick and case is almost as quick (and pleasantly POSIX-compatible).

@F. Hauri 2013-12-08 23:06:09

As these Stack Overflow answers tell mostly about Bash, I've posted a case independent Bash function at the very bottom of this post...

Anyway, there is my

Compatible answer

As there are already a lot of answers using Bash-specific features, there is a way working under poorer-featured shells, like BusyBox:

[ -z "${string##*$reqsubstr*}" ]

In practice, this could give:

string='echo "My string"'
for reqsubstr in 'o "M' 'alt' 'str';do
  if [ -z "${string##*$reqsubstr*}" ] ;then
      echo "String '$string' contain substring: '$reqsubstr'."
    else
      echo "String '$string' don't contain substring: '$reqsubstr'."
    fi
  done

This was tested under Bash, Dash, KornShell (ksh) and ash (BusyBox), and the result is always:

String 'echo "My string"' contain substring: 'o "M'.
String 'echo "My string"' don't contain substring: 'alt'.
String 'echo "My string"' contain substring: 'str'.

Into one function

As asked by @EeroAaltonen here is a version of the same demo, tested under the same shells:

myfunc() {
    reqsubstr="$1"
    shift
    string="[email protected]"
    if [ -z "${string##*$reqsubstr*}" ] ;then
        echo "String '$string' contain substring: '$reqsubstr'.";
      else
        echo "String '$string' don't contain substring: '$reqsubstr'."
    fi
}

Then:

$ myfunc 'o "M' 'echo "My String"'
String 'echo "My String"' contain substring 'o "M'.

$ myfunc 'alt' 'echo "My String"'
String 'echo "My String"' don't contain substring 'alt'.

Notice: you have to escape or double enclose quotes and/or double quotes:

$ myfunc 'o "M' echo "My String"
String 'echo My String' don't contain substring: 'o "M'.

$ myfunc 'o "M' echo \"My String\"
String 'echo "My String"' contain substring: 'o "M'.

Simple function

This was tested under BusyBox, Dash, and, of course Bash:

stringContain() { [ -z "${2##*$1*}" ]; }

That's all folks!

Then now:

$ if stringContain 'o "M3' 'echo "My String"';then echo yes;else echo no;fi
no
$ if stringContain 'o "M' 'echo "My String"';then echo yes;else echo no;fi
yes

... Or if the submitted string could be empty, as pointed out by @Sjlver, the function would become:

stringContain() { [ -z "${2##*$1*}" ] && [ -z "$1" -o -n "$2" ]; }

or as suggested by Adrian G√ľnter's comment, avoiding -o switches:

stringContain() { [ -z "${2##*$1*}" ] && { [ -z "$1" ] || [ -n "$2" ];};}

Final (simple) function:

And inverting the tests to make them potentially quicker:

stringContain() { [ -z "$1" ] || { [ -z "${2##*$1*}" ] && [ -n "$2" ];};}

With empty strings:

$ if stringContain '' ''; then echo yes; else echo no; fi
yes
$ if stringContain 'o "M' ''; then echo yes; else echo no; fi
no

Case independent (Bash only!)

For testing strings without care of case, simply convert each string to lower case:

stringContain() {
    local _lc=${2,,}
    [ -z "$1" ] || { [ -z "${_lc##*${1,,}*}" ] && [ -n "$2" ] ;} ;}

Check:

stringContain 'o "M3' 'echo "my string"' && echo yes || echo no
no
stringContain 'o "My' 'echo "my string"' && echo yes || echo no
yes
if stringContain '' ''; then echo yes; else echo no; fi
yes
if stringContain 'o "M' ''; then echo yes; else echo no; fi
no

@Eero Aaltonen 2013-12-10 08:35:24

This would be even better, if you can figure out some way to put that to a function.

@F. Hauri 2014-05-06 18:23:46

@EeroAaltonen How do you find my (new added) function?

@eggmatters 2014-07-15 20:20:36

I know! find . -name "*" | xargs grep "myfunc" 2> /dev/null

@F. Hauri 2014-07-15 22:14:14

@eggmatters Question stand for string that contain string (not file containing string).

@eggmatters 2014-07-16 23:15:05

@F.Hauri Sorry, was a joke to your comment to EuroAaltonen The find command has absolutely nothing to do with the question posted on this thread.

@Eero Aaltonen 2014-09-25 11:15:14

$F.Hauri It is what I was thinking and hoping for. The only change I would make is to the name. I propose "stringContain", since at least integers are supported.

@Sjlver 2014-10-24 12:14:28

This is wonderful because it's so compatible. One bug, though: It does not work if the haystack string is empty. The correct version would be string_contains() { [ -z "${2##*$1*}" ] && [ -n "$2" -o -z "$1" ]; } A final thought: does the empty string contain the empty string? The version above things yes (because of the -o -z "$1" part).

@user3439968 2014-11-14 19:11:04

+1. Very good! For me I changed order stringContain() { [ -z "${1##*$2*}" ] && [ -z "$2" -o -n "$1" ]; }; "Search where" "Find what". Work in busybox. Accepted answer above don't work in busybox.

@Arun Sangal 2016-10-21 22:13:28

Similarly, if [ -z ${string%%*$subreqstr*} ]; then echo there; else echo not-there; fi #will work too.

@F. Hauri 2017-08-25 20:53:26

@ArunSangal Yes, this is technicaly same way of thinking, but there could be some difference in practice... I would let you try to bench this over some thousand of tests to see if bash could be worst in one way, than the other... ;-)

@F. Hauri 2018-02-12 15:30:22

Special case: The string to search for is the first word in each lines (processor in /proc/cpuinfo) see this answer to How to obtain the number of CPUs/cores in Linux from the command line?!

@Adrian Günter 2018-04-10 16:39:13

The -a and -o extensions to [ are not exactly portable as POSIX specifies behavior to only four operators. [ -n "$2" ] && [ -z "${2##*$1*}" ] || [ -z "$1" ] is portable and follows the behavior of implementations from other languages, although I think switching the arguments would be clearer yet (haystack before needle).

@F. Hauri 2018-04-11 14:50:04

@AdrianGünter As [ is a command and && a separation between two commands, [ -z "$1" -o -n "$2" ] only have to be considered, there are no more than four operators (in fact two operators as -n and -z use implicit operators).

@Adrian Günter 2018-04-12 00:55:40

@F.Hauri I was lazily referring to both operators (-a, -o, -n, -z, ...) and primaries/operands ($1, $2, ...) as operators (or better yet, arguments) to [ (AKA test). Point being, [ -z "$1" -o -n "$2" ] is passing five arguments to [ which is unspecified and therefore unreliable and unportable. See: unix.stackexchange.com/a/57843/83127 and pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html >4 arguments: The results are unspecified.

@F. Hauri 2018-04-12 06:20:01

@AdrianGünter. Hem.. care in translating boolean: a & ( b | c ) is not same than c & b | a !

@tripleee 2018-04-12 06:49:00

Even Busybox has case, I believe.

@Adrian Günter 2018-04-12 17:48:22

@F.Hauri I changed the order here to further optimize, but [ -z "$1" ] || [ -n "$2" ] && [ -z "${2##*$1*}" ] and [ -z "${2##*$1*}" ] && { [ -z "$1" ] || [ -n "$2" ] } are functionally equivalent, except that your version is less efficient. Consider: if $1, the needle/search substring, is empty ("") then you do not need to test for [ -z "${2##*$1*}" ] at all, as every string (including an empty one!) contains "". If $1 is an empty string strContain should always return success (0). If you test our versions side-by-side you should find them to be functionally equivalent.

@Pryftan 2018-12-21 14:29:58

Is it really a poorer shell? It's maybe more limited but it's statically linked isn't it? That's great for system recovery (of some mistakes or errors) and other such things. Maybe it's not ever necessary to have this functionality in such situations but you never know. This really complements the other answers!

@Sandburg 2019-01-11 08:33:53

That's nice to say if something is bash, ksh or vanilla shell compatible, thx

@Yordan Georgiev 2013-08-26 10:13:42

This Stack Overflow answer was the only one to trap space and dash characters:

# For null cmd arguments checking   
to_check=' -t'
space_n_dash_chars=' -'
[[ $to_check == *"$space_n_dash_chars"* ]] && echo found

@Peter Mortensen 2020-01-01 13:43:32

It is an answer to this same question.

@Kurt Pfeifle 2012-07-01 11:31:45

I found to need this functionality quite frequently, so I'm using a home-made shell function in my .bashrc like this which allows me to reuse it as often as I need to, with an easy to remember name:

function stringinstring()
{
    case "$2" in
       *"$1"*)
          return 0
       ;;
    esac
    return 1
}

To test if $string1 (say, abc) is contained in $string2 (say, 123abcABC) I just need to run stringinstring "$string1" "$string2" and check for the return value, for example

stringinstring "$str1" "$str2"  &&  echo YES  ||  echo NO

@elyase 2012-12-11 21:34:39

[[ "$str" == $substr ]] && echo YES || echo NO

@nyuszika7h 2014-06-11 18:08:55

I'm pretty sure the x hack is only required for very old shells.

@andreas 2010-08-27 19:19:19

Try oobash.

It is an OO-style string library for Bash 4. It has support for German umlauts. It is written in Bash.

Many functions are available: -base64Decode, -base64Encode, -capitalize, -center, -charAt, -concat, -contains, -count, -endsWith, -equals, -equalsIgnoreCase, -reverse, -hashCode, -indexOf, -isAlnum, -isAlpha, -isAscii, -isDigit, -isEmpty, -isHexDigit, -isLowerCase, -isSpace, -isPrintable, -isUpperCase, -isVisible, -lastIndexOf, -length, -matches, -replaceAll, -replaceFirst, -startsWith, -substring, -swapCase, -toLowerCase, -toString, -toUpperCase, -trim, and -zfill.

Look at the contains example:

[Desktop]$ String a testXccc
[Desktop]$ a.contains tX
true
[Desktop]$ a.contains XtX
false

oobash is available at Sourceforge.net.

@Mark Baker 2008-10-27 14:57:44

You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an if with a [ or a [[. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use grep, and not the [ command.

Just do:

if grep -q foo <<<"$string"; then
    echo "It's there"
fi

Now that you are thinking of if as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?

## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...

## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...

The -q option makes grep not output anything, as we only want the return code. <<< makes the shell expand the next word and use it as the input to the command, a one-line version of the << here document (I'm not sure whether this is standard or a Bashism).

@alex.pilon 2011-10-20 17:03:14

they are called here strings (3.6.7) I believe it is bashism

@larsr 2011-12-19 12:45:23

one can also use Process Substitution if grep -q foo <(echo somefoothing); then

@nyuszika7h 2014-06-11 18:05:53

Note that echo is unportable, if you're passing a variable, use printf '%s' "$string instead.

@Bruno Bronosky 2015-03-28 07:10:24

@nyuszika7h echo alone is pretty portable. The flags are not. If you find yourself thinking about -e or -n use printf

@F. Hauri 2015-04-20 08:40:48

The cost of this is very expensive: doing grep -q foo <<<"$mystring" implie 1 fork and is bashism and echo $mystring | grep -q foo implie 2 forks (one for the pipe and the second for running /path/to/grep)

@tripleee 2018-04-12 06:45:29

@BrunoBronosky echo without flags might still have unexpected portability problems if the argument string contains backslash sequences. echo "nope\c" is expected on some platforms to work like echo -e "nope" on some others. printf '%s' "nope" vs printf '%s\n' 'nope\c'

@ahoffer 2018-06-06 05:07:08

@TechZilla Remember, we are talking about a Bash script. No one would write a Bash script for performance critical code.

@Matt Tardiff 2008-10-23 20:10:53

If you prefer the regex approach:

string='My string';

if [[ $string =~ "My" ]]
then
   echo "It's there!"
fi

@blast_hardcheese 2012-02-14 05:10:19

Had to replace an egrep regex in a bash script, this worked perfectly!

@bukzor 2013-06-05 18:15:56

The =~ operator already searches the whole string for a match; the .*'s here are extraneous. Also, quotes are generally preferable to backslashes: [[ $string =~ "My s" ]]

@seanf 2015-05-12 00:55:47

@bukzor Quotes stopped working here as of Bash 3.2+: tiswww.case.edu/php/chet/bash/FAQ E14). It's probably best to assign to a variable (using quotes), then compare. Like this: re="My s"; if [[ $string =~ $re ]]

@KrisWebDev 2016-01-24 14:57:20

Test if it does NOT contain a string: if [[ ! "abc" =~ "d" ]] is true.

@Douwe van der Leest 2018-08-01 11:40:09

Note that the order in which the test occurs matters. The output of the following line of code will be forward 2. number=2; if [[ "1, 2, 4, 5" = *${number}* ]]; then echo forward $number; fi; if [[ *${number}* = "1, 2, 4, 5" ]]; then echo backwards $number; fi;

@Adam Bellaire 2008-10-23 12:55:24

You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:

string='My long string'
if [[ $string == *"My long"* ]]; then
  echo "It's there!"
fi

Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside.

@Quinn Taylor 2009-07-30 17:14:51

Also note that you can reverse the comparison by just switching to != in the test. Thanks for the answer!

@Jonik 2010-11-16 11:20:14

Hmm, with this exact code, I get [[: not found. Any idea what's wrong? I'm using GNU bash, version 4.1.5(1), on Ubuntu.

@Paused until further notice. 2010-12-17 05:18:19

@Jonik: You may be missing the shebang or have it as #!/bin/sh. Try #!/bin/bash instead.

@GuruM 2011-09-07 10:37:20

+1 for your answer. Thanks. I was looking at some code which uses this syntax. Though I guessed at the intention now I've got confirmation. Tried the bash scripting guide and google for quite some time but couldn't find what I wanted until I saw your answer. Can you give a link to such uses of strings and wildcard matching? Thanks!!

@prolink007 2012-10-19 16:32:53

@DennisWilliamson I am getting the same problem as Jonik, but i have the correct #!/bin/bash at the top. What else could be causing the problem?

@prolink007 2012-10-19 16:48:56

I figured out the issue. If you are calling the script from another script make sure you are using bash nameofscript.sh instead of sh nameofscript.sh.

@Redsandro 2012-12-05 20:06:57

No success. What is wrong with this statement? if [["Oh My God" == *My*]]; then echo Yes! ; else echo no.. ; fi It returns no. This is in bash/Ubuntu 12.10

@Paul Price 2013-01-22 16:43:56

Leave a space between the brackets and the contents.

@Orwellophile 2013-08-09 05:07:17

You don't need to quote variables inside [[ ]]. This will work just as well: [[ $string == $needle ]] && echo found

@Reinstate Monica Please 2014-01-09 00:28:14

+1 to the original answer. But the edit is at best subjective and at worst inaccurate (you don't need to quote $string here, though doing so may be a good practice), and should obviously be rolled back.

@Dss 2014-01-13 16:57:27

This doesn't seem to work when I have a colon ":" in the string if [[ $string == My: test ]]

@user3153014 2014-06-11 05:45:59

how to check whether string contains * ?

@nyuszika7h 2014-06-11 17:53:09

@Orwellophile Careful! You can only omit the double quotes in the first argument to [[. See ideone.com/ZSy1gZ

@Orwellophile 2014-06-24 14:24:53

@nyuszika7h - what a mess :) i would have used a regular expression, which you can't quote in bash4 anyway.

@redolent 2014-07-24 18:01:35

By the way, make sure the asterisks are not in quotes: if [[ " $args" == *" -l"* ]]

@Shailen 2014-08-03 14:56:24

It took me a long while to realise that with #!/bin/bash, spaces are needed between each element of a statement, e.g if [[ $input_var == "test" ]]

@Tim S. 2014-11-19 16:16:45

@Dss mentioned that it was the space, just thought I'd add you need to escape it: if [[ $string == *My\ String* ]]

@harish 2015-02-18 16:46:01

I had used above with only difference i had the string & substring switched places in the comparison and did not work for me, Had me stumped for a while. Anyone know why?

@F. Hauri 2015-05-31 14:36:26

Warning: It's a so called bashism! As @DennisWilliamson pointed out, this work only under bash, but not with regular shell! ( I've wrote a compatible function which could work under poor shell like busybox )

@maxschlepzig 2017-04-30 15:11:08

@F.Hauri, this is not a bashism. It also works with POSIX sh and ksh.

@maxschlepzig 2017-04-30 15:21:24

@VasyaNovikov, 'Word splitting and pathname expansion are not performed on the words between the [[ and ]]' (bash(1))

@VasiliNovikov 2017-04-30 20:08:48

@maxschlepzig right. I didn't know that when I was writing the comment.. Will delete the old comment and this one in a couple of hours..

@F. Hauri 2017-05-01 05:33:15

@maxschlepzig You're wrong: It's bashisms! Care that your /bin/sh is not a link to bash! For myself, I just tried dash now: dash: 2: [[: not found

@maxschlepzig 2017-05-01 09:58:56

@F.Hauri, POSIX 2008 lists [[ as unspecified reserved word. But still: KSH 88 and the /usr/xpg4/bin/sh under Solaris 10 ('a standards compliant shell') both understand [[. Thus, it is NOT a bashism.

@sdaau 2017-10-26 19:18:34

I've noticed, if you run this if [[ $string == *"linux"* ]]; then command in a directory that contains file 'README.linux', then *"linux"* will expand to README.linux, that is * will glob - and so the matching will fail.

@Fredrick Gauss 2017-11-07 06:51:38

Attention! if [[ *"My long"* == $string ]]; does not work whereas if [[ $string == *"My long"* ]]; works. Is there anyone to explain this?

@Yongwei Wu 2018-01-19 07:46:23

@sdaau Not reproduced under Bash with my test. No globbing happened. The bash info page actually clearly says: "Word splitting and filename expansion are not performed on the words between the '[[' and ']]'"

@Yongwei Wu 2018-01-19 07:49:14

@FredrickGauss The Bash info page says: "When the '==' and '!=' operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in *note Pattern Matching::. If the shell option 'nocasematch' (see the description of 'shopt' in *note The Shopt Builtin::) is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches ('==') or does not match ('!=')the pattern, and 1 otherwise. Any part of the pattern may be quoted to force it to be matched as a string."

@Alexander Mills 2018-05-02 06:23:16

why not use == instead of =?

@Glen Thomas 2019-04-25 21:08:23

This is not working for me in bash 4.4

@user 2019-11-04 03:12:44

It will throw an syntax error if the $string variable is empty. Can you fix it?

@Ethan Post 2018-04-11 02:09:50

I use this function (one dependency not included but obvious). It passes the tests shown below. If the function returns a value > 0 then the string was found. You could just as easily return 1 or 0 instead.

function str_instr {
   # Return position of ```str``` within ```string```.
   # >>> str_instr "str" "string"
   # str: String to search for.
   # string: String to search.
   typeset str string x
   # Behavior here is not the same in bash vs ksh unless we escape special characters.
   str="$(str_escape_special_characters "${1}")"
   string="${2}"
   x="${string%%$str*}"
   if [[ "${x}" != "${string}" ]]; then
      echo "${#x} + 1" | bc -l
   else
      echo 0
   fi
}

function test_str_instr {
   str_instr "(" "'[email protected] (dev,web)'" | assert_eq 11
   str_instr ")" "'[email protected] (dev,web)'" | assert_eq 19
   str_instr "[" "'[email protected] [dev,web]'" | assert_eq 11
   str_instr "]" "'[email protected] [dev,web]'" | assert_eq 19
   str_instr "a" "abc" | assert_eq 1
   str_instr "z" "abc" | assert_eq 0
   str_instr "Eggs" "Green Eggs And Ham" | assert_eq 7
   str_instr "a" "" | assert_eq 0
   str_instr "" "" | assert_eq 0
   str_instr " " "Green Eggs" | assert_eq 6
   str_instr " " " Green "  | assert_eq 1
}

@Peter Mortensen 2020-01-01 14:22:10

The suspense! What is the dependency?

@Ethan Post 2020-01-02 05:47:49

The "str_escape_special_characters" function. It is in GitHub arcshell_str.sh file. arcshell.io will get you there.

@Eduardo Cuomo 2016-11-10 14:56:18

Exact word match:

string='My long string'
exactSearch='long'

if grep -E -q "\b${exactSearch}\b" <<<${string} >/dev/null 2>&1
  then
    echo "It's there"
  fi

@ride 2016-03-03 19:12:33

I like sed.

substr="foo"
nonsub="$(echo "$string" | sed "s/$substr//")"
hassub=0 ; [ "$string" != "$nonsub" ] && hassub=1

Edit, Logic:

  • Use sed to remove instance of substring from string

  • If new string differs from old string, substring exists

@Zulan 2016-03-05 14:04:26

Please add some explanation. Imparting the underlying logic is more important than just giving the code, because it helps the OP and other readers fix this and similar issues themselves

@chemila 2011-11-11 05:51:10

One is:

[ $(expr $mystring : ".*${search}.*") -ne 0 ] && echo 'yes' ||  echo 'no'

@michael 2013-08-10 05:50:44

expr is one of those swiss-army-knife utilities that can usually do whatever it is you need to do, once you figure out how to do it, but once implemented, you can never remember why or how it's doing what it's doing, so you never touch it again, and hope that it never stops doing what it's doing.

@michael 2014-03-04 19:13:26

@AloisMahdal I never down-voted, I'm just postulating on why downvotes were given. A cautionary comment. I do use expr, on rare occasion, when portability prevents using bash (eg., inconsistent behavior across older versions), tr (inconsistent everywhere) or sed (sometimes too slow). But from personal experience, whenever re-reading these expr-isms, I have to go back to the man page. So, I would just comment that every usage of expr be commented...

@tripleee 2016-02-10 18:12:41

There was a time when all you had was the original Bourne shell. It lacked some commonly required features, so tools like expr and test were implemented to perform them. In this day and age, there are usually better tools, many of them built into any modern shell. I guess test is still hanging in there, but nobody seems to be missing expr.

@kevinarpe 2012-12-01 15:41:25

This also works:

if printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
  printf "Found needle in haystack"
fi

And the negative test is:

if ! printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
  echo "Did not find needle in haystack"
fi

I suppose this style is a bit more classic -- less dependent upon features of Bash shell.

The -- argument is pure POSIX paranoia, used to protected against input strings similar to options, such as --abc or -a.

Note: In a tight loop this code will be much slower than using internal Bash shell features, as one (or two) separate processes will be created and connected via pipes.

@michael 2013-08-10 05:43:32

...but the OP doesn't say which version of bash; e.g., older bash's (such as solaris frequently has) may not include these newer bash features. (I've run into this exact problem (bash pattern matching not implemented) on solaris w/ bash 2.0)

@nyuszika7h 2014-06-11 18:03:49

echo is unportable, you should be using printf '%s' "$haystack instead.

@kevinarpe 2014-08-16 11:15:44

@nyuszika7h: I was not away echo is unportable. Will /bin/echo work?

@nyuszika7h 2014-08-16 11:18:03

Nope, just avoid echo altogether for anything but literal text without escapes that doesn't start with a -. It may work for you, but it's not portable. Even bash's echo will behave differently depending on whether the xpg_echo option is set. P.S.: I forgot to close the double quote in my previous comment.

@kevinarpe 2015-03-17 04:52:25

@nyuszika7h: Do you know if printf -- <anything> is portable or only printf <anything>? Out of habit, I used printf -- <anything> to be safe.

@nyuszika7h 2015-03-17 13:45:38

@kevinarpe I'm not sure, -- is not listed in the POSIX spec for printf, but you should use printf '%s' "$anything" anyway, to avoid issues if $anything contains a % character.

@kevinarpe 2016-06-17 07:14:01

@nyuszika7h: Regarding support for --, I found this POSIX spec for getopt(): pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.ht‌​ml. Do you think it is safe to assume that if printf is POSIX defined / compatible, then -- will also be supported?

@nyuszika7h 2016-06-17 10:49:39

@kevinarpe Based on that, it probably is.

@Jahid 2015-04-28 19:55:58

[[ $string == *foo* ]] && echo "It's there" || echo "Couldn't find"

@nicodjimenez 2017-10-16 21:11:17

I will add that the echo "Couldn't find statement at the end is a nice trick to return 0 exit statuses for these matching commands.

@Jahid 2017-10-17 05:56:16

@nicodjimenez you can not target exit status any more with this solution. Exit status is swallowed up by the status messages ...

@nicodjimenez 2017-10-17 10:02:32

That's exactly what I meant... If you don't have || echo "Couldn't find" then you will return an error exit status if there is no match, which you might not want if you're running a CI pipeline for example where you want all commands to return non error exit statuses

@Jadu Saikia 2008-12-21 14:27:17

grep -q is useful for this purpose.

The same using awk:

string="unix-bash 2389"
character="@"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'

Output:

Not Found

string="unix-bash 2389"
character="-"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'

Output:

Found

Original source: http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html

@nyuszika7h 2014-06-11 18:14:36

echo is unportable, you should be using printf '%s' "$string" instead. I'm editing the answer because the user doesn't appear to exist anymore.

@Stefan 2009-02-09 06:15:45

How about this:

text="   <tag>bmnmn</tag>  "
if [[ "$text" =~ "<tag>" ]]; then
   echo "matched"
else
   echo "not matched"
fi

@user49586 2009-02-09 06:37:25

=~ is for regexp matching, hence too powerful for the OP's purpose.

@ephemient 2008-10-23 14:35:45

The accepted answer is best, but since there's more than one way to do it, here's another solution:

if [ "$string" != "${string/foo/}" ]; then
    echo "It's there!"
fi

${var/search/replace} is $var with the first instance of search replaced by replace, if it is found (it doesn't change $var). If you try to replace foo by nothing, and the string has changed, then obviously foo was found.

@TPoschel 2010-10-08 12:41:48

ephemient's solution above: > ` if [ "$string" != "${string/foo/}" ]; then echo "It's there!" fi` is useful when using BusyBox's shell ash. The accepted solution does not work with BusyBox because some bash's regular expressions are not implemented.

@nitinr708 2017-08-01 08:58:26

the inequality of difference. Pretty weird thought! I love it

@venimus 2019-07-12 17:31:56

unless your string is 'foo' though

@BuvinJ 2019-10-15 20:25:00

I wrote this same solution myself (because my interpreter wouldn't take the top answers) then went looking for a better one, but found this!

@Marcus Griep 2008-10-23 12:47:04

I am not sure about using an if statement, but you can get a similar effect with a case statement:

case "$string" in 
  *foo*)
    # Do stuff
    ;;
esac

@technosaurus 2014-01-04 17:02:32

This is probably the best solution since it is portable to posix shells. (a.k.a. no bashisms)

@P.P 2015-12-17 23:27:44

@technosaurus I find it rather odd to criticize "bashism" in a question that has only bash tag :)

@Carl Smotricz 2016-06-03 07:56:28

@P.P. It's not so much a criticism as the preference of a more universal solution over a more limited one. Please consider that, years later, people (like me) will stop by to look for this answer and may be pleased to find one that's useful in a wider scope than the original question. As they say in the Open Source world: "choice is good!"

@maxschlepzig 2017-05-01 10:00:33

@technosaurus, FWIW [[ $string == *foo* ]] also works in some POSIX compliant sh versions (e.g. /usr/xpg4/bin/sh on Solaris 10) and ksh (>= 88)

@technosaurus 2017-05-01 22:28:28

@maxschlepzig ... not if there are characters in $IFS such as space, newline, tab or user defined separator... case statement works though without wierd mixed quotation or having to push and pop IFS

@maxschlepzig 2017-05-01 22:39:28

@technosaurus, you mean because of word-splitting? With [[ there is no word-splitting (cf. e.g. ksh(1)). This example string="hello foo world"; [[ $string == *foo* ]] && echo true works for me as expected. Even with ksh 88. Yes, in a fresh shell that has the default IFS value (i.e. space+newline+tab).

@tripleee 2018-04-12 06:40:25

@maxschlepzig Then they are not POSIX compliant. Ksh is obviously Korn shell, not POSIX sh; and Solaris 10 XPG sh is definitely not POSIX.

@maxschlepzig 2018-04-12 18:58:15

@tripleee, nobody claimed that ksh is POSIX sh. And you are wrong about XPG4: 'superset of POSIX.1-1990, POSIX.2-1992, and POSIX.2a-1992 containing extensions to POSIX standards from XPG3' XPG4(5). You can also ask yourself what sh version Sun used to get certified as POSIX compliant.

@tripleee 2018-04-13 03:57:22

Then by the same logic Bash is POSIX. It is simply misleading to say that this is a feature in some POSIX shells; it is definitely a non-POSIX feature and so whether those shells are POSIX or not is kind of beside the point. Like you say, the shell contains extensions beyond POSIX.

@Ray Foss 2019-03-25 14:50:53

Busybox ash does not handle asterisks in [[ ... the case-switch did work!

Related Questions

Sponsored Content

66 Answered Questions

[SOLVED] How to get the source directory of a Bash script from within the script itself

  • 2008-09-12 20:39:56
  • Jiaaro
  • 1639066 View
  • 4796 Score
  • 66 Answer
  • Tags:   bash directory

67 Answered Questions

[SOLVED] What is the difference between String and string in C#?

62 Answered Questions

[SOLVED] How to replace all occurrences of a string?

4 Answered Questions

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

30 Answered Questions

[SOLVED] How to concatenate string variables in Bash

25 Answered Questions

[SOLVED] Case insensitive 'Contains(string)'

23 Answered Questions

[SOLVED] How do I check if a string contains another string in Objective-C?

36 Answered Questions

[SOLVED] How do I check if a string contains a specific word?

34 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3797033 View
  • 1594 Score
  • 34 Answer
  • Tags:   java string

Sponsored Content