Tobias Erdle's Blog

Writes mostly about Java, Jakarta EE and software development in general. All views are my own.

Github: erdlet | E-Mail:

How to clone a Git repository checking out a specific branch


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 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.