13
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
  • 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]' – Valentin Bajrami Oct 22 '17 at 18:42
  • 8
    @val0x00ff but 123456 is a valid RE – roaima Oct 22 '17 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. – Valentin Bajrami Oct 22 '17 at 19:11
26

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

string=123456
if [[ "$string" =~ 123456 ]]; then echo 123; fi
123
  • @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 '17 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 '17 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 '17 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.