Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkout existing remote branch

Tags:

git

github

I have seen different ways to checkout existing remote branch:

Suppose my friend has pushed new branch 'bigbug' and I want to check out and switched my local working copy to that branch, I have below options:

1. git checkout -b bigbug origin/bigbug

2. git checkout -t origin/bigbug

3. git fetch
   git checkout bigbug

Are all above three options available in current git release and valid? If all are valid then is there any difference between them and which one to use?

like image 395
Nitesh Virani Avatar asked Jul 04 '15 18:07

Nitesh Virani


People also ask

How do I checkout a remote branch with a different name?

To be precise, renaming a remote branch is not direct – you have to delete the old remote branch name and then push a new branch name to the repo. Step 2: Reset the upstream branch to the name of your new local branch by running git push origin -u new-branch-name .


1 Answers

The base for the checkout command is:

git checkout --[options] <local branch> <remote>/<tracked branch>

When you perform a git checkout -b bigbug origin/bigbug you are saying to Git to execute two commands:

  1. git branch bigbug origin/bigbug (git creates a branch with name bigbug and setup tracking to origin/bigbug)
  2. git checkout bigbug (git changes your workspace to match bigbug branch)

When you perform git checkout -t origin/bigbug you are saying to Git to execute the same two commands above. The difference is that it will name the local branch with the same name of the remote branch (in the first example you can change the name of the remote branch to whichever you want). The -t options is the same of --track.

In your last command, when you run: git fetch you tell Git to lookup on the remote repositories for new commits, branches, etc. Then when you run git checkout bigbug you tell it to change the workspace to match the bigbug branch. If you have a local branch with that name, Git will checkout it. If not, it will look the remote branches to one matching name and then create a local branch with the same name.

So, when you use one or another it depends of what you want. Most of the time they will work as the same (except in the last example, when you already have a local branch with the same name of a remote branch). The most importante thing is to know exactly what the command and options do and combine them accordingly to what you want.

like image 142
Lucas Saldanha Avatar answered Oct 09 '22 18:10

Lucas Saldanha