Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant get "=~" to work. Keep getting "[: =~: binary operator expected" [closed]

Tags:

bash

When I try and use if [ "$1" =~ "$regex" ]; then

I keep on getting back the same error: [: =~: binary operator expected

Here is an example function where I get the error:

char_check() {
  regex='^[]0-9a-zA-Z,!^`@{}=().;/~_|[-]*$'
  if [ "$1" =~ "$regex" ]; then
    echo "No illegal characters."
  else
    echo "Illegal characters."
  fi
}

Any response would be a great help.

like image 383
Matty Avatar asked Mar 07 '26 15:03

Matty


1 Answers

Regular expressions require [[ expression ]] as shown in the man page of bash.

Also you must not quote the regex itself, e.g. you should prefer $regex over "$regex"

char_check() {
  regex='^[]0-9a-zA-Z,!^`@{}=().;/~_|[-]*$'
  if [[ "$1" =~ $regex ]]; then
    echo "No illegal characters."
  else
    echo "Illegal characters."
  fi
}

If you quote the regex then you are trying to match the string, not the pattern. In other words it will match the weird string '^[]0-9a-zA-Z,!^`@{}=().;/~_|[-]*$'

like image 145
vdavid Avatar answered Mar 09 '26 03:03

vdavid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!