The former will checkout the remote branch, this usually results in the following warning:
You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
You end up with a detached HEAD when you check out a commit that has not a local branch pointing to it. This means that while you can do whatever you want with it, when you commit changes, there is no branch pointing to the commits you create. The only pointer pointing at it is HEAD which is a transient pointer that changes whenever you switch the branch.
So committing with a detached HEAD essentially means that all commits you create will be lost, if you don’t create a branch later that points to them.
You can do that, as the warning points out, with git checkout -b branch_name
. This creates a new branch that points to HEAD and checks out that branch, putting you back into a safe situation.
Now, when you do git checkout -b <branch> origin/<branch>
you basically do both at once: You check out origin/<branch>
and also create a local branch called <branch>
that points to that checked out version (and you also switch to that branch). So you end up in a safe situation immediately.
For that purpose, the command is identical to this:
# check out the remote branch into a detached HEAD
git checkout origin/<branch>
# create a new branch from the HEAD and check that branch out
git checkout -b <branch>
And also identical to this:
# create a new local branch pointing to the remote branch
git branch <branch> origin/<branch>
# check out that branch
git checkout <branch>
Btw. there is a useful shortcut when dealing with new remote branches. For example if the remote has a branch foo
and you don’t have a local branch foo
yet, you can just do git checkout foo
and Git will recognize that you probably want to create a local branch foo
that tracks the remote branch origin/foo
.