20
string=123456

if [ $string == 123456 ]; then
echo 123
fi

This works fine, but if I change == to =~ I get this error:

./test: line 3: [: =~: binary operator expected
3
  • The use of =~ is in this case wrong. =~ compares the patter (left side of the assignment) with a regular expresion regex on the right side of the assinment. A regular expression in its simplest form is passed like '[0-9][0-9]' Oct 22, 2017 at 18:42
  • 9
    @val0x00ff but 123456 is a valid RE Oct 22, 2017 at 19:01
  • @roaima agreed, however regex is known for its engine, back-referencing, character-set, meta chars denoting starting of a string, ending of a string etc. Oct 22, 2017 at 19:11

1 Answer 1

36

Bash's regex matching works only within double square brackets [[ ... ]]:

string=123456
if [[ "$string" =~ 123456 ]]; then echo 123; fi
123
3
  • @Kusalananda: Regarding the edit, the quotes are not required on the left hand side of a double bracket expression [[ ... ]], since no word splitting or pathname expansion occurs there. They are only needed when using single brackets [ ... ] (both sides) and on the right hand of the double bracket expression.
    – user000001
    Oct 23, 2017 at 11:21
  • @user000001 while you're correct, it's much better just to quote all variables by reflex unless there's a necessity not to. It's a much safer habit.
    – Joe
    Oct 27, 2017 at 20:00
  • @Joe: Agreed, when in doubt, quote... I only mentioned this because it was an edit to an already correct answer. Had it been there from the first revision I would not have commented on this.
    – user000001
    Oct 28, 2017 at 13:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .