It’s common to use short-lived branches to organize your work into individual
features, instead of committing directly onto persistent “mainline” branches
like master
. This:
But even if you don’t commit directly onto a local master branch, you still often need to refer to the remote master branch to do things like:
You don’t need to have a locally checked out master branch to do any of that:
git already allows you to refer to remote branches directly, via remote
tracking branches, like
origin/master
.
git diff origin/master
git merge origin/master
(usually after a git fetch origin
; or just do git pull origin master
in one step)git branch my-new-branch origin/master
Sometimes you need more direct access to the content at master. E.g., maybe you want to just do a build at master, without necessarily starting a new topic branch.
You can do this using detached
heads. In addition to
checking out branches, git lets you check out arbitrary commits. So you can
just checkout a remote tracking branch directly, with git checkout
origin/master
.
Why not just checkout master? Because it’s simpler not to: If you checkout
master locally, you now need to mentally deal with your local view of the
remote master (origin/master
) and your local copy of master (master
),
which can diverge.
E.g., without a local master branch, bringing in changes from master is git
pull origin master
. If you have a local copy of master (and you don’t want
it to become stale), you’d instead need to:
# starting with a feature branch checked out
git checkout master
git pull origin master
git checkout -
git merge master
↩ January 22, 2019