How do I open the link to my Github repo by running a command from the terminal?

Viewed 327

I want to visit the webpage for my repo:

Github.com/myUsername/myRepoName

After navigating in my terminal to the myRepoName directory, can I run a command to open that link in my browser?

1 Answers

TL;DR

Such a functionality is not built-in to Git, but it's easy to implement as an alias or script-based command.

Caveat

The exact answer to your question will depend on your operating system and which Git distro you're using, and what type of URL you use in your repos, but at least one of my two solutions below should be fairly easy to adapt to most systems.

Solution option 1: create an alias

Here is a alias that works in my Git for Windows ~/.gitconfig assuming an https URL for my remotes, and with no error checking:

[alias]
    browse-remote = !/c/Program\\ Files\\ \\(x86\\)/Google/Chrome/Application/chrome.exe $(git remote show origin | grep Fetch.URL | sed 's/.*http/http/')

In Git Bash, I then CD into a repo and type git browse-remote to launch the remote in Chrome.

If you want to use this idea, you'll have to set the browser path correctly, and make sure the part extracting the URL is working correctly on your machine.

Solution option 2: write a script

I've just written a script with some error checking that works more nicely. Tested in Git Bash on Windows, but should be easy to adapt to Linux or Mac.

Call this file git-browse-remote:

#!/bin/bash

# Set this to your browser
BROWSER='/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'

set -o pipefail
if URL=$(git remote show origin | grep Fetch.URL | sed 's/.*http/http/'); then
   "$BROWSER" "$URL"
else
   echo git-browse-remote: Could not extract repo URL from the output of \"git remote show origin\"
   exit 1
fi

Run chmod +x git-browse-remote and place the file somewhere on your PATH.

Then typing git browse-remote will open the remote in your browser if it's an http(s) link, or issue an error message if you're not inside a repo or if the remote URL is not an http(s) one.

Heck, I like this solution enough, I just installed in on my own machine. What a good idea, thanks for asking the question!

What about SSH URLs?

If you're using ssh-based remote URLs, like git@github.com:user/repo.git, I would take solution 2 and add some URL transformation logic to the script.

Related