Nitesh Virani
Nitesh Virani

Reputation: 1712

Checkout existing remote branch

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?

Upvotes: 19

Views: 33627

Answers (1)

Lucas Saldanha
Lucas Saldanha

Reputation: 891

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.

Upvotes: 36

Related Questions