Get URL's redirect target with curl

There is an even easier way

curl -w "%{url_effective}\n" -I -L -s -S $URL -o /dev/null

it would print

http://raspberrypi.stackexchange.com/questions/1508/how-do-i-access-the-distributions-name-on-the-command-line/1521

for URL

http://raspberrypi.stackexchange.com/a/1521/86

Try this:

$ LOCATION=`curl -I http://raspberrypi.stackexchange.com/a/1521/86 | perl -n -e '/^Location: (.*)$/ && print "$1\n"'`
$ echo "$LOCATION"
/questions/1508/how-do-i-access-the-distributions-name-on-the-command-line/1521#1521

Google Redirects

Google redirect URLs are slightly different. They return a Javascript redirect, which could easily be processed, but why not process the original URL and for go curl all together?

$ URL="http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CFAQFjAA&url=http%3A%2F%2Fwww.raspberrypi.org%2F&ei=rv8oUODIIMvKswa4xoHQAg&usg=AFQjCNEBMoebclm0Gk0LCZIStJbF04U1cQ"
$ LOCATION=`echo "$URL" | perl -n -e '/url=([a-zA-Z0-9%\.]*)/ && print "$1\n"'`
$ echo "$LOCATION"
http%3A%2F%2Fwww.raspberrypi.org%2F
$ echo "$LOCATION" | perl -pe 's/%([0-9a-f]{2})/sprintf("%s", pack("H2",$1))/eig'
http://www.raspberrypi.org/

Reference

  1. For url decode...

curl can be configured to follow redirects and to print variables after completion. So what you ask can be achieved with the following command:

curl -Ls -w %{url_effective} -o /dev/null https://google.com

The man page explains the necessary parameters like that:

-L, --location          Follow redirects (H)
-s, --silent            Silent mode (don't output anything)
-w, --write-out FORMAT  Use output FORMAT after completion
-o, --output FILE       Write to FILE instead of stdout

Tags:

Url

Curl