How do I switch to a new branch in git
I have cloned a git repository and I would like to switch to a particular branch from the following list (e.g. branch1, branch2, branch3
)
Should I have to say git fetch origin branch2
?
How do I know that I have switched to开发者_开发技巧 this particular branch on my local repository?
How do I switch to say 'branch3' from 'branch2'?
Recent versions of git have enough DWIM ("Do What I Mean!") logic to understand you just doing:
git checkout branch1
... in that situtation. That will work if there is no local branch called branch1
, and there's only one remote-tracking branch that ends with branch1
- in that case it's equivalent to the longer:
git checkout --track -b branch1 origin/branch1
... which should work in every circumstance.
I realize that I missed answering some of your later questions. git stores the state of the branches from the origin
repository in so-called "remote-tracking branches" - these are the ones that look like origin/master
, origin/branch1
, origin/branch2
, etc. If you want to update all of these from origin
just use:
git fetch origin
To see all of your remote-tracking branches, you can use:
git branch -r
The meaning of the full command I quoted above:
git checkout --track -b branch1 origin/branch1
... is:
- create and switch to a new branch called
branch1
(thecheckout -b branch1
bit) - start it at
origin/branch1
(i.e. base it on the lastest cached state ofbranch1
fromorigin
) - and mark
origin/branch1
as being "upstream" ofbranch1
in your git config (the--track
bit, although that's actually implied if the start point is a remote-tracking branch)
I assume you want to switch to remote branch. If you just cloned the repo then there should be a default remote called origin
(you can view your remote repos via git remote -v
.
To switch (or checkout) a remote branch: git checkout -t origin/BRANCH_NAME
- this says you want to change your working directory contents to the remote branch BRANCH_NAME
associated with the remote pointed to by origin
. This will create something called a "tracking branch" which will set up a local branch to mirror the remote branch.
To check out what branch you're on type: git branch
. To switch back to master at any time simply do a git checkout master
精彩评论