0

I'm trying to check if given string contains another. It should go like:

Case 1: "abc" in "abc" # True

Case 2: "ab" in "abc" # True

Case 3: "x" in "abc" # False

if test $(findstring "ab", "abc"); then \
    echo "YES"; \
else \
    echo "NO "; \
fi;

# NO

It seems that findstring is matching words only but not searching substrings (it is not correct for Case 2). Is there another simple way to do it?

Meroz
  • 859
  • 2
  • 8
  • 28
  • 1
    Note make doesn't treat quotes as special in any way. It's just another character as far as make as concerned, like `x` or `q`. So your call is not right: you would want to run `$(findstring ab,abc)`, without quotes. That would expand to the empty string if it wasn't found, or else the matched string. – MadScientist Mar 09 '23 at 13:02

1 Answers1

1

You are mixing make syntax and shell syntax. Generally, you want to use shell syntax in recipes.

target: prerequisites
    case "abc" in *"ab"*) echo yes;; *) echo no;; esac

For further variations, see also How to check if a string contains a substring in Bash

The [ aka test command is somewhat brittle. If you know your shell is actually Bash, you can use [[; but then you separately have to tell make that (SHELL := /bin/bash) and this obviously makes your code less portable.

othertarget: other prereqs
    if [[ "abc" = *"ab"* ]]; then echo yes; else echo no; fi
    # if the commands are simple, a convenient shorthand:
    [[ "abc" = *"ab"* ]] && echo yes || echo no

Your problem with findstring is that "ab" really isn't a substring of "abc" (it would be a substring of "ab"c).

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • somehow first and second solution shows me "no" in all cases. Third one works fine but also empty string *""* is considered as True/match? – Meroz Mar 09 '23 at 10:03
  • 1
    Sorry, my bad, the `*"substring"*` syntax only works with `[[`. Answer updated. I can't repro the empty string case; `case "" in *"ab"*) echo yes;; *) echo no;; esac` prints `no` for me. – tripleee Mar 09 '23 at 10:32
  • Thanks for correction. The case is: `case "abc" in *""*) echo yes;; *) echo no;; esac` gives yes, I would expect no. First string is "searched string" and second "substring", so when substring is empty then it shows "yes". – Meroz Mar 09 '23 at 10:41
  • 1
    Every string has the empty string as a substring. What other result could you possibly expect? After quote removal the pattern simply becomes `**` which is every possible string (twice!) – tripleee Mar 09 '23 at 10:48