Joseph O'Shea

Quickly open repo on GitHub from shell

shellcligit

Background / Motivation

Often after running git push, you want to go to GitHub to open a PR. Why not have a shell command that does it for you?

How to do it

if you're using bash

Place this script in "$HOME/dev/cli-tools/openRepoOnGithub.sh"

You can of course us any other directory if you prefer. Just be sure to use the same directory in the "shell alias" section

#!/bin/bash

# Use `git remote -v` to list remotes, grab the first line, extract the URL, and remove the `.git` suffix if present
url=$(git remote -v | awk 'NR==1{print $2}' | sed 's/\.git$//')

# If the URL starts with a Git SSH path, convert it to an HTTPS URL
if [[ $url =~ git@github.com:(.+) ]]; then
    url="https://github.com/${BASH_REMATCH[1]}"
fi

# Use the `open` command to open the URL in the default browser on MacOS
open $url

Shell alias

Add this to $HOME/.bashrc and/or $HOME/.bash_profile (whichever you use)

alias opengh="$HOME/dev/cli-tools/openRepoOnGithub.sh" 

Remeber to reload your shell!

Quick reload:

source "$HOME/.bashrc"

if you're using zsh

The script

Place this script in "$HOME/dev/cli-tools/openRepoOnGithub.sh"

You can of course us any other directory if you prefer. Just be sure to use the same directory in the "shell alias" section

#!/bin/zsh

# Use `git remote -v` to list remotes, grab the first line, extract the URL, and remove the `.git` suffix if present
url=$(git remote -v | awk 'NR==1{print $2}' | sed 's/\.git$//')

# If the URL starts with a Git SSH path, convert it to an HTTPS URL
if [[ $url =~ git@github.com:(.+)$ ]]; then
    url="https://github.com/${match[1]}"
fi

# Use the `open` command to open the URL in the default browser on MacOS
open $url

Shell alias

Add this to $HOME/.zshrc

alias opengh="$HOME/dev/cli-tools/openRepoOnGithub.sh" 

Caveats / Pitfalls

This only works if your remote is on GitHub and matches the pattern git@github.com. It should be fairly easy to modify the script to work with other remotes. To do so: