Cameron Ball
Cameron Ball

Reputation: 4128

Why doesn't this simple bash regex return true?

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?

Upvotes: 5

Views: 736

Answers (2)

Maroun
Maroun

Reputation: 96018

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

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174836

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

[[ "0" =~ ^[0-9]+$ ]]

Upvotes: 5

Related Questions