Bash – Condition regex error

bashshell-script

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

Best Answer

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

string=123456
if [[ "$string" =~ 123456 ]]; then echo 123; fi
123
Related Question