Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this simple bash regex return true?

Tags:

regex

bash

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?

like image 282
Cameron Ball Avatar asked May 21 '15 08:05

Cameron Ball


2 Answers

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

[[ "0" =~ ^[0-9]+$ ]]
like image 128
Avinash Raj Avatar answered Oct 10 '22 05:10

Avinash Raj


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
like image 20
Maroun Avatar answered Oct 10 '22 05:10

Maroun