1

When I run this script:

#!/bin/bash

if [[ "abcd" =~ ^.*$ ]]; then
    echo "something"
fi

I get:

./tmp2.sh: line 3: conditional binary operator expected
./tmp2.sh: line 3: syntax error near `=~'
./tmp2.sh: line 3: `if [[ "abcd" =~ ^.*$ ]]; then'

I've tried all suggestions I've found, but still the same:/ Help me, please!

user3521479
  • 565
  • 1
  • 5
  • 12

4 Answers4

6

Given that you're seeing a bash-specific error message, we can rule out that something other than bash is running the script (if it were a POSIX-features-only shell, such as sh on some systems, you'd instead see an error message relating to [[).

The most likely explanation:

  • Your bash version is < 3.0, and therefore doesn't support the =~ operator.
    • To verify, run echo $BASH_VERSION in your script.

The specific error you're seeing is bash's way of saying: "I'm seeing a string I don't recognize as an operator."

mklement0
  • 382,024
  • 64
  • 607
  • 775
3

Run your script with bash script.sh not sh script.sh. It probably would also work with ./script.sh if script.sh is already executable since you're using the header #!/bin/bash.

konsolebox
  • 72,135
  • 12
  • 99
  • 105
1

this should work

re='^.*$'
if [[ "abcd" =~ $re ]]; then
  echo "something"
fi
Bad_Coder
  • 1,019
  • 1
  • 20
  • 38
  • 1
    It would be helpful to explain the syntax. Please expand on your answer. – David Brossard Jul 12 '14 at 15:02
  • 3
    This wouldn't help. The `=~` syntax works in all versions of Bash starting 3.0. – konsolebox Jul 12 '14 at 16:44
  • While storing your regex in an auxiliary variable does help in some situations (with regexes that contain `\ `-prefixed sequences such as `\<` or `\s`), this is NOT the problem here - yours an the OP's code are equivalent. – mklement0 Jul 12 '14 at 19:31
0

This is almost identical to the error you get in all versions of bash that support regex if you put ~= rather than =~.

Martin
  • 2,316
  • 1
  • 28
  • 33
  • How is this answering the question? – Toto May 11 '20 at 16:32
  • Because I came here from google trying to investigate why I was getting "conditional binary operator expected" and it wasn't until I copied the example from here did I spot the obvious error. It looks almost identical to the error listed above and I have spent quite a while searching for this resolution. If you are on this page with that error and you haven't checked the =~ it is probably a far more common reason it's not working. – Martin May 11 '20 at 16:36
  • May be, but this doesn't answer actual question and shouldn't be here, SO is not a forum. – Toto May 11 '20 at 17:26
  • 1
    When you google "stack overflow" "syntax error near" "~=", this page is top of the list. It is not immediately obvious that google has swapped the =~ for you. This post answers that related question. – Martin May 12 '20 at 09:29