I have used fetch
followed by checkout
...
git fetch <remote> <rbranch>:<lbranch>
git checkout <lbranch>
... where <rbranch>
is the remote branch or source ref and <lbranch>
is the as yet non-existent local branch or destination ref you want to track and which you probably want to name the same as the remote branch or source ref. This is explained under options in the explanation of <refspec>
.
Git is so smart it auto completes the first command if I tab after the first few letters of the remote branch. IE: I don't even have to name the local branch, Git automatically copies the name of the remote branch for me. Thanks Git!
Also as the answer in this similar SO post shows, if you don't name the local branch in fetch
, you can still create it when you check it out by using the -b
flag. IE: git fetch <remote> <branch>
followed by git checkout -b <branch> <remote>/<branch>
does exactly the same as my initial answer. And evidently if your repo has only one remote, then you can just do git checkout <branch>
after fetch
and it will create a local branch for you. EG: You just cloned a repo and want to check out additional branches from the remote.
I believe that some of the documentation for fetch
may have been copied verbatim from pull
. In particular the section on <refspec>
in options is the same. However, I do not believe that fetch
will ever merge
, so that if you leave the destination side of the colon empty fetch
should do nothing.
NOTE: That git fetch <remote> <refspec>
is short for git fetch <remote> <refspec>:
which would therefore do nothing, but git fetch <remote> <tag>
is the same as git fetch <remote> <tag>:<tag>
which should copy the remote <tag>
locally.
I guess this is only helpful if you want to copy a remote branch locally, but not necessarily check it out right away. Otherwise I now would use the accepted answer above, which is explained in detail in the first section of the checkout description and later in the options section under the explanation of --track
, since it's a 1-liner. Well... sort of a 1-liner, because you would still have to run git fetch <remote>
first.
FYI: The order of the <refspecs>
(source:destination) explains the bizarre pre Git-1.7 method for deleting remote branches. IE: Push nothing into the destination refspec.
git fetch --all
, Then to view all the branches:git branch
, Then I checkout the branch:git checkout nameofnewbranch
– Jeff Mattson Sep 20 '17 at 17:24