1

I have the following piece of code where I am trying to match the word "test" in the given string:

str="some test string"

if [ $str == *"test"* ]; then # [: too many arguments
    echo "string was found"
else
    echo "string was not found"
fi

Output:

string was not found

Bash version:

GNU bash, version 4.4.23(1)-release (x86_64-pc-msys)

What am I doing wrong?

8
  • 1
    if [[ "$str" == *"test"* ]]; then (Note the quotes around $str and the double [[ ]]) Commented Oct 29, 2021 at 9:58
  • @0stone0 there is where I tried from and I still get the same output and an error saying [: too many arguments Commented Oct 29, 2021 at 9:59
  • Are you sure you're using bash? PLease share the version. The above should work as you can test in this online demo Commented Oct 29, 2021 at 10:00
  • 1
    When using [, the LHS operand always needs to be quoted "$str" Commented Oct 29, 2021 at 10:06
  • 3
    @meJustAndrew [ ] and [[ ]] have significantly different syntaxes, and only [[ ]] can do pattern matching like you're trying to do. You must switch to the double-bracket version for this. See BashFAQ #13: "What is the difference between test, [ and [[ ?" and the Unix & Linux question "What is the difference between the Bash operators [[ vs [ vs ( vs ((?" Commented Oct 29, 2021 at 10:38

1 Answer 1

2

this part [ $str == *"test"* ] is evaluated as a file-pattern glob. And if you have several files in that dir starting with test, you get "too many arguments"

Essentially, this is being evaluated [ $str == somethingttest testish test ], but [] with == wants only three arguments.

Another problem is using patterns with [ ]. It's not supported afaik. If you want to match against a pattern use [[ $foo =~ PATTERN ]], or [[ $str =~ test ]] in your case.

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

3 Comments

That was brilliant! I had indeed one file locally called test. Removing it made the error go away, but the string was still not found. And after adding two sets of square braces instead of one the string got matched. Thanks a lot!
btdt... np. just stick to double brackets unless you have reasons not to, they are much safer.
[[ .. ]] supports both shell patterns (*test*) with = or ==, or regular expressions with =~. In other words, [[ $str == *test* ]] would work as well. Notice that the left-hand side is quoted for us, so we don't have to take care of it (it wouldn't hurt, though), and the right-hand side must not be quoted or the pattern isn't recognized as such.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.