0

The regular expression I have put into the conditional construct (with the =~ operator) would not return the value as I had expected, but when I assign them into two variables it worked. Wondering if I had done something wrong.

Version 1 (this one worked)

a=30
b='^[0-9]+$' #pattern looking for a number
[[ $a =~ $b ]]
echo $?

#result is 0, as expected

Version 2 (this one doesn't work but I thought it is identical)

[[ 30 =~ '^[0-9]+$' ]]
echo $?

#result is 1

1 Answer 1

4

Don't quote the regular expression:

[[ 30 =~ ^[0-9]+$ ]]
echo $?

From the manual:

Any part of the pattern may be quoted to force the quoted portion to be matched as a string.

So if you quote the entire pattern, it's treated as a fixed string match rather than a regular expression.

Sign up to request clarification or add additional context in comments.

3 Comments

Also, I recommend putting the pattern in a variable and using the unquoted variable in the match expression: pattern='^[0-9]+$' and [[ 30 =~ $pattern ]] - this allows you to include characters such as whitespace in the pattern.
@DennisWilliamson The question already shows how to do it using a variable, he was just wondering why it didn't work with a literal.
Back to remedial reading for me! But it's useful to point out why a variable should be used and not a literal pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.