Quickly Copy the Latest Commit URL

From time to time, it’s helpful to send a coworker the GitHub commit URL for the latest commit in a repository. While you can navigate to GitHub, find the commit links, and manually copy it, using a custom CLI command makes this super easy!

The script to copy the commit URL is pretty simple, but it handles all the complexity of parsing the remote URL into a proper URL.

#!/usr/bin/env bash

# Default to the latest commit if no commit was provided
commit=${1:-$(git rev-parse --short HEAD)}

# Read the repo base URL from the git config
url=$(git config --get remote.origin.url)

# Take the git@hostname.com:account/repo.git format and turn it into
# https://hostname.com/account/repo/commit/...
if [[ $url != "https://"* ]]; then
	url=$(echo "$url" | sed 's/\.git$//' | sed 's/:/\//' | sed 's/^git@/https:\/\//')

echo "$url/commit/$commit"

Now we can print the commit URL in our terminal by running the following command:


The script is nice enough to support passing a commit URL, which is useful to get the full GitHub URL for a given commit hash.

commit-url 0dbad3ee

Bonus tip!

The base commit-url command will print the commit URL, which makes the command very robust allowing us to pipe the output into other commands or including it in a larger shell script. But often we just want to copy the URL to our clipboard.

Like many of my other bash commands, I solve this by adding a similarly named script that will copy the result of the command to the clipboard automatically.

#!/usr/bin/env bash

commit-url "$1" | pbcopy

Now we can simply add an exclamation point when running the command and we’ll copy it to the clipboard instead of printing it. Neat, right!?


Want to learn more about shell scripts? Take a look at my full-length blog post about embracing shell scripts to improve your developer workflow.