Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to check if a string contains a substring in Bash

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.

Answer*

Draft saved
Draft discarded
Cancel
7
  • 3
    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. Commented Aug 10, 2013 at 5:50
  • @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... Commented Mar 4, 2014 at 19:13
  • 2
    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. Commented Feb 10, 2016 at 18:12
  • 1
    Upvoting since I needed something that worked in Bourne shell, and everything else appears to be bash-specific. Commented May 3, 2021 at 23:11
  • expr: syntax error: unexpected argument ‘.*.*’ bash: [: -ne: unary operator expected Commented Jul 14, 2022 at 16:49

lang-bash

AltStyle によって変換されたページ (->オリジナル) /