Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git checkout branch from outside

Problem: I need somehow to checkout an existing branch of a project that is already cloned locally on my file system without being in that particular folder of this project.

Solution: I'm trying to do the following:

  1. git clone 'github-project-url' 'file-system-folder'
  2. git checkout 'existing-branch' 'file-system-folder'

I do realize that second step is not quite right, but I also am trying to avoid to cd 'file-system-folder'.

like image 528
eistrati Avatar asked May 20 '11 14:05

eistrati


People also ask

Can you checkout a remote branch in git?

In order to checkout a remote branch you have to first fetch the contents of the branch. In modern versions of Git, you can then checkout the remote branch like a local branch. Older versions of Git require the creation of a new branch based on the remote .

How do I fetch a remote branch?

To view your remote branches, simply pass the -r flag to the git branch command. You can inspect remote branches with the usual git checkout and git log commands. If you approve the changes a remote branch contains, you can merge it into a local branch with a normal git merge .

How do I force checkout a branch?

Force a Checkout You can pass the -f or --force option with the git checkout command to force Git to switch branches, even if you have un-staged changes (in other words, the index of the working tree differs from HEAD ). Basically, it can be used to throw away local changes.


2 Answers

You can use --git-dir to specify the .git directory to use as the repository, and --work-tree to specify the working tree to to the checkout in. See the git man page for details.

git --git-dir=file-system-folder/.git --work-tree=file-system-folder checkout existing-branch 
like image 172
Brian Campbell Avatar answered Sep 30 '22 17:09

Brian Campbell


Since Git version 1.8.5, you can also use -C <path> option. Be sure to use it before any other command:

git -C ~/my-git-repo checkout master

Note that it doesn't have to be specifically the .git folder. Here is the man documenation:

-C <path>        Run as if git was started in <path> instead of the current         working directory. When multiple -C options are given, each        subsequent non-absolute -C <path> is interpreted relative to        the preceding -C <path>.         This option affects options that expect path name like --git-dir        and --work-tree in that their interpretations of the path names        would be made relative to the working directory caused by the -C option.        For example the following invocations are equivalent:             git --git-dir=a.git --work-tree=b -C c status            git --git-dir=c/a.git --work-tree=c/b status 
like image 43
General Redneck Avatar answered Sep 30 '22 18:09

General Redneck