0

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;
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
MightyPork
  • 18,270
  • 10
  • 79
  • 133
  • [Recommended reading on Regular Expressions in Bash](http://mywiki.wooledge.org/BashGuide/Patterns#Regular_Expressions-1) – Tom Fenech Feb 18 '15 at 10:26
  • Regarding your latest deleted question. As you deleted it, I was typing an answer based on one of my [previous answers](http://stackoverflow.com/questions/10894692/python-outfile-to-another-text-file-if-exceed-certain-file-size); perhaps it will help – Mike Pennington Feb 22 '15 at 13:11
  • @MikePennington I just wanted to avoid any more downvotes, after I found out that `global` is not needed there at all, it was all clear. – MightyPork Feb 22 '15 at 13:15

1 Answers1

2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643