Category Archives: git

Opening github in your browser from the terminal

Here is my first ever bash function! When you run it from the terminal it opens the github page in your browser for the git repository you are currently in. In keeping with bash best practices it has a short simple name: gh. I find myself doing this quite a lot as I prefer the github log and history views to the gitx or command line views.

# Opens the github page for the current git repository in your browser
# git@github.com:jasonneylon/dotfiles.git
# https://github.com/jasonneylon/dotfiles/
function gh() {
  giturl=$(git config --get remote.origin.url)
  if [ "$giturl" == "" ]
    then
     echo "Not a git repository or no remote.origin.url set"
     exit 1;
  fi

  giturl=${giturl/git\@github\.com\:/https://github.com/}
  giturl=${giturl/\.git/\/tree/}
  branch="$(git symbolic-ref HEAD 2>/dev/null)" ||
  branch="(unnamed branch)"     # detached HEAD
  branch=${branch##refs/heads/}
  giturl=$giturl/tree/$branch
  open $giturl
}

Just type gh:
Opening github from the terminal

Boom! github!
The github page for the repository

How it works

It grabs the remote url via the git config command: git@github.com:jasonneylon/dotfiles.git. Next it does some simple string replacements to get a github http url: https://github.com/jasonneylon/dotfiles/. Finally it open the github url in the default browser using the MacOS open command. As it uses the open command I imagine it only works on MacOSs.