MightyPork
MightyPork

Reputation: 18881

bash if [[ =~ regex compare not working?

I have a value in a variable that may be absolute or relative url, and I need to check which one it is.

I have found that there's a =~ operator in [[, but I can't get it to work. What am I doing wrong?

url="http://test"
if [[ "$url" =~ "^http://" ]];
    then echo "absolute.";
fi;

Upvotes: 0

Views: 130

Answers (1)

anubhava
anubhava

Reputation: 785481

You need to use regex without quote:

url="http://test"
if [[ "$url" =~ ^http:// ]]; then
    echo "absolute."
fi

This outputs `absolute. as regex needs to be without quote in newer BASH (after BASH v3.1)

Or avoid regex and use glob matching:

if [[ "$url" == "http://"* ]]; then
    echo "absolute."
fi

Upvotes: 2

Related Questions