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.
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,!^`@{}=().;/~_|[-]*$'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With