5

If I do [[ "0" =~ "^[0-9]+$" ]] && echo hello at a terminal I would expect to see the word "hello"

However, nothing gets printed. What am I doing wrong?

2
  • 1
    [[ "0" =~ ^[0-9]+$ ]] Commented May 21, 2015 at 8:20
  • Recommended reading Commented May 21, 2015 at 9:04

2 Answers 2

5

You need to remove the double quotes present in your regex. ie, don't enclose your regex pattern within double quotes.

[[ "0" =~ ^[0-9]+$ ]]
Sign up to request clarification or add additional context in comments.

Comments

3

It should be:

[[ "0" =~ ^[0-9]+$ ]] && echo hello

Note that the second part is not surrounded with double quotes, otherwise it'll be treated as the string "^[0-9]+$" and not a regex. To confirm that, try:

[[ "^[0-9]+$" =~ "^[0-9]+$" ]] && echo hello

1 Comment

Slight technicality: the right hand side is still treated as a regular expression ([[ foo =~ "fo" ]] would still succeed, for example). The difference is that any metacharacters inside the regex will be treated literally.

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.