Using CURL in a script

Hi all

so I'm new to scripting but I am making a script that is a url shortener. It will take a url off the command line and spit back the shortened version using bit.ly's api

this is what I have so far

if [ $# -lt 1 ]
then
        echo "You must supply a URL."
        exit 1
fi

read url
curl "https://api-ssl.bitly.com/v3/shorten?access_token=xxxxxxxxxxxxxxxxxxxxxx&longUrl=$url"

curl -d

I am not entirely sure if I am using this correctly. I know curl will fetch the direct URL for the conversion but I dont know if it is legal to stuff '$url' directly into the http address. Curl -d will post the data but I'm a bit confused as to what URL I'm supposed to use there. . .

basically what i want to do is fetch the url off the command line and stuff it into that http address after '&longURL=' where the url is supposed to be. Then I need to fetch back the shortened version of the address.

this is the api
ApiDocumentation - bitly-api - bitly REST API method documentation - API Libraries and Documentation for bitly - Google Project Hosting
and this is the page ive been reading regarding curl
cURL - Tutorial

I believe curl -d will post data granted I provide the information after it to post it but I dont know what should go after curl -d. .I am new to using APIs and im just picking this up

any help is appreciated thank you

I just tried and it takes GET arguments, -d will POST data.

curl "https://api-ssl.bitly.com/v3/shorten/?login=<user>&apiKey=<key>&format=txt&longUrl=$url"

works for me.

Also you said it takes URL from command line, you'd simply use $1 instead of "read url" which would prompt again

If you need more help with the script, please let us know the target shell -- posix, ksh, bash, etc.

1 Like

thanks for the reply I am using bash shell

as for posting data, how can I use 'curl -d' to post the short URL? Is it going to automatically return the short URL on its own or is there a specific address I need to use from the API?

I am looking at this here

ApiDocumentation - bitly-api - bitly REST API method documentation - API Libraries and Documentation for bitly - Google Project Hosting

thanks again

For shell scripting I'd recommend using format=txt and then the result is simply the shortened url. This may get you started

#!/bin/bash

if (( $# < 1 )); then
    echo "You must supply a URL."
    exit 1
fi

if short=$(curl "https://api-ssl.bitly.com/v3/shorten?access_token=xxxxxxxxxxxxxxxxxxxxxx&format=txt&longUrl=$1" 2>/dev/null); then
    echo "Short URL: $short"
else
    echo "Communication error"
fi