In this case, when do I have to pass the -b parameter? What is the difference between the below when the remote does exist
The difference is that if you pass the -b
flag, git
creates a new branch with the name you give and based on the branch you were in when you created that branch. Without the flag, git
will look for an existing branch, including one in any remote repos that you're tracking, and switch to one of those if if finds one.
So, let's say: 1) you're currently in your own branch called foo
; 2) you've got a remote called upstream
; and 3) that remote has a branch called bar
. If you say:
git checkout bar
then you'll switch to a local copy of the foo
branch on upstream
(assuming your repo already knows about foo
because you've recently done a git fetch
). In other words, if you do:
git diff upstream/bar
then git
will report no differences.
But, if you give the -b
flag:
git checkout -b bar
then git
will create a new branch that happens to also be named bar
, but that will have the same content as the foo
branch that you were just in. In other words:
git diff upstream/bar
will report the differences between upstream
's bar
branch and your local bar
branch (which, again, got its content from your foo
branch).
It's easy to try this yourself. Just pick two existing remote branches that don't exist locally, say upstream/branch1
and upstream/branch2
on your remote that you know have some differences. Verify that there are differences with git diff upstream/branch1 upstream/branch2
. Now checkout the first branch without the -b
flag:
git checkout branch1
Now you should have a local branch called branch1
. Again, check that this matches the upstream version: git diff upstream/branch1 branch1
. There should be no differences. Next, try creating a branch2
using the -b
flag:
git checkout -b branch2
Now you should have a local branch2
, but it should match what's in branch1
and also upstream/branch1
. Verify:
git diff upstream/branch1 branch2 # should be no diffs
git diff upstream/branch2 branch2 # should be like diffing branch1 and upstream/branch2