Extract Final URL After Curl Follows Redirect

When working with APIs, web scraping, or automated scripts, you often need to find the ultimate destination of a URL that goes through one or more HTTP redirects. This article demonstrates how to configure the curl command-line tool to follow these redirects and cleanly output only the final resolved URL, bypassing the response body entirely.

The Standard Command

To extract the final URL, use the following curl command:

curl -Ls -o /dev/null -w "%{url_effective}\n" http://bit.ly/3Y9Xp2t

How the Command Works

The command combines several of curl’s built-in options to silence unnecessary output and extract only the target metadata:

Saving the Output to a Variable in Bash

If you are writing a shell script, you can capture the final URL directly into a variable for further processing:

FINAL_URL=$(curl -Ls -o /dev/null -w "%{url_effective}" http://bit.ly/3Y9Xp2t)
echo "The final destination is: $FINAL_URL"

This method is highly efficient because it performs the redirect resolution in a single network pass without downloading the payload of the final page.