← til

Shorten Github link from the command line

March 12, 2019
github

There's a tool for shortening links from Github that I've known for a while but I imagine not everyone is aware of it.

It's called git.io, and the best thing about it is that you can use it from the command line with curl.

Use it like this:

curl -si https://git.io -F "url=https://github.com/rails/rails" | grep -Fi Location

I use it all the time for linking to anything that's on Github from code comments. The most recent example is linking to a deprecated Rails method, deep_merge which is available on this link:

https://github.com/rails/rails/blob/c0c87922baf47eed64a53d3afceba978bb175da9/activesupport/lib/active_support/core_ext/hash/diff.rb/#L9

That's a huge link, so it's much better to have it shortened to:

https://git.io/fhjSr

The advantage for using this instead of some other link shortening service is that you can be sure it's a link to Github since it only allows shortening of Github links.

Bonus points if you turn it into a script:

#!/usr/bin/env bash

url=$1

# Append http:// to links without it.
url=$(sed '/^http/! s/^/http:\/\//' <<< $url)
# Convert http:// to https:// since git.io requires HTTPS.
url=$(sed 's/^http:/https:/' <<< $url)

curl -si https://git.io -F "url=$url" |
  grep -Fi Location |
  cut -d ' ' -f 2

And call it with:

shorten github.com/rails/rails