0

I'm trying to determine if a substring (a file name) is present in a large string containing many file paths. This is my code which just doesn't work (prints "Does not contain"). I tried comparing with =~, different quotes usages. Nothing from that seems to work. Do you please see a problem in my code?

#!/bin/bash

text="/path/to/some/file1-2-3.json /another/path/to/file4-5-6.json"
my_file="file1-2-3.json"

if [[ *"$my_file"* == "$text" ]]; then
    echo "Contain"
else
    echo "Does not contain"
fi

1 Answer 1

1

it works if you invert the strings:

$ more script.sh
#!/bin/bash

text="/path/to/some/file1-2-3.json /another/path/to/file4-5-6.json"
my_file="file1-2-3.json"

if [[ "$text" == *"$my_file"* ]]; then
        echo "Contain"
else
        echo "Does not contain"
fi
$ ./script.sh
Contain
$

form man bash:

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 under Pattern Matching...

Sign up to request clarification or add additional context in comments.

1 Comment

I was just writing my own question as I've just found out. What an unpleasant bug! :-D Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.