Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash check for http or https regex

Tags:

bash

I'm trying to check if a url starts with http|https and ends with jpg|png. I have searched, but the answers don't work for me.

I have this currently:

if [[ $url = ^https?://.*jpg ]]
then
wget -O webcam.jpg $url
fi

But its fails to wget. What am I doing wrong?

like image 395
meister Avatar asked Sep 19 '26 13:09

meister


1 Answers

You have to use the =~ operator for regular-expression matching; = only does pattern matching. The equivalent pattern would be http?(s)://*jpg*. (Recent versions of bash always use extended patterns inside [[ ... ]]; older versions may require they be turned on explicitly with shopt -s extglob.)

(I added the trailing * to the pattern because patterns are anchored to both ends of the string by default, while regular expressions require ^ and $ explicitly. Since you did not have $ at the end of your regular expression, I made the pattern open at the end as well.)

like image 109
chepner Avatar answered Sep 21 '26 09:09

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!