Tobias Erdle's Blog

Development Engineer working with different technologies. Former Jakarta MVC & Eclipse Krazo Committer. All views are my own.

Github: erdlet | E-Mail: blog (at) erdlet (punkt) de

How to clone a Git repository checking out a specific branch

TL;DR

Use git clone -b <branch-name> <repo-url> <directory> to clone a Git repository into a specific directory while checking out a specified branch.

The situation

Sometimes there may be the requirement to check out a repository twice, but based on different branches. An example where I had this requirement was the update of the Eclipse Krazo documentation in our GitHub Pages branch. Because the diff was too big, a simple checkout of the GH Pages branch didn't clean up the repository as expected. Also, I had to copy files between the master and gh-pages branches. So a solution had to be found to

  1. Clone the Krazo repository and directly check out the gh-pages branch
  2. Clone the repo into another directory to avoid a name collision with the existing clone

The solution

The solution is this command: git clone -b <branch-name> <repo-url> <directory>. This command clones the remote repo into the given directory and checks out the defined branch. So git clone -b gh-pages git@github.com:eclipse-ee4j/krazo.git krazo-gh-pages cloned the Krazo repository to krazo-gh-pages and checked out the gh-pages branch, so I could work on the homepage independent from the Java code.