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:
- git clone 'github-project-url' 'file-system-folder'
- 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'".
git 2.5 added the ability to have multiple working trees using git worktree. So this case, you'd use something like
git worktree add -b new-branch-name ../dir-name existing-branch
you can then change to dir-name and make your commits as usual. The commits will end up in your original repository (where you used
worktree add
).When you're done and everything you want is committed, you can delete the
dir-name
folder and rungit worktree prune
to clean up the orphaned worktree in your repo.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 thegit
man page for details.You're quite welcome to use
--git-dir
and--work-tree
to avoid cd'ing, but honestly, it's easier just to cd. To avoid having to cd back, you can do it in a subshell:Of course, in this specific case, you don't actually need two commands:
You can also use -C as an option now. Be sure ot use it before any other command such as
git -C ~/my-git-repo checkout master
Note that it doesn't have to be specifically the .git folder. Here is the man documenation: