Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why check out master before creating a new branch?

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?

like image 787
lakesare Avatar asked Dec 11 '22 01:12

lakesare


2 Answers

TL;DR

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.

More detailed answer

What git checkout -b newbranch does

To 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,

enter image description here

by running git checkout -b newbranch, you would end up with

enter image description here

Where Michael Hartl is leading you

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):

enter image description here

So, why check out 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:

enter image description here

Then, running

git checkout -b newbranch

will definitely create the new branch where desired:

enter image description here

A more direct approach: two birds, one stone...

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.

like image 89
jub0bs Avatar answered Dec 25 '22 09:12

jub0bs


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.

like image 22
GreyBeardedGeek Avatar answered Dec 25 '22 08:12

GreyBeardedGeek