I'm reading the Rails Tutorial book and, over and over, the author asks the reader to run the following two commands:
$ git checkout master
$ git checkout -b a
I understand what these commands do: they check out the master
branch, and then create and check out a new branch named a
.
Why do we need the first line at all? Does it make some difference, or can I just leave it out?
Why do we need the first line at all? [...]
This is a slightly roundabout way of making sure that the new branch, a
, points at the same commit as master
does.
git checkout -b newbranch
doesTo fix ideas, you can think of the HEAD
pointer as a You-are-here mark on the subway map that is your commit graph. Now, the following command,
git checkout -b newbranch
creates and checks out a new branch called newbranch
that points to the same commit that HEAD
(directly or indirectly) points to. For instance, if your repo looked as follows,
by running git checkout -b newbranch
, you would end up with
However, Michael Hartl (author of the Rails Tutorial) wants you to create and check out a new branch that points to a particular commit: the tip of your master
branch (i.e. the commit that the master
branch points to):
master
first?By asking you to run
git checkout master
Michael Hartl is simply making sure that your HEAD
points (indirectly) to the right commit, i.e. the tip of master
:
Then, running
git checkout -b newbranch
will definitely create the new branch where desired:
Having to first check out master
may seem a bit unwieldy, though. You can actually condense those two commands into one:
git checkout -b newbranch master
No matter where you are in your repo (i.e. where HEAD
points to), this command will create and checkout a new branch called newbranch
that points at the tip of master
.
However, because the Rails tutorial is meant to cater for people who are new to Git, and because
git checkout -b newbranch master
is a bit more advanced and perhaps less intuitive than
git checkout master
git checkout -b newbranch
you can't really blame Michael Hartl for recommending the latter.
When you branch, you branch from a specific commit. Checking out master makes sure that your new branch starts from the head (most recent commit) of the master branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With