Creating branch off of remote master

kidA picture kidA · Oct 17, 2014 · Viewed 13.9k times · Source

I have problem understanding the logic behind the following command in Git:

git checkout -b hotfix_example_1 origin/master

If I type it then a local branch called hotfix is created that branches off of the master branch of my remote repository named origin. When I later push it to my remote repository the graph looks like this:

enter image description here

Say that a colleague makes changes and pushes them to the remote master branch and at some later point I decide to create another branch off of the remote master one called hotfix_example_2. When I push the new hotfix_example_2 branch to the remote repository I notice that the new branch I created is not branched off of the latest commit of remote master (the one that my colleague pushed earlier) but instead is branched off of the commit before that. If I do a

git pull origin master

on my local master branch and repeat the procedure, I can see that hotfix_example_2 is branched off of my colleague's commit. What I don't get is why do I have to do a git pull to get the graph I want even though I use origin/master in my checkout -b command. I am really sorry if it does not make much sense but english is not my native language.

Answer

Dark Falcon picture Dark Falcon · Oct 17, 2014

Pretty much only pull and fetch retrieve new commits and update remote remote refs. Other operations only work on your local copy. When you create a branch, it is created off the specified ref, but that ref is looked up in the local repository only. You can see what this ref currently is for each remote branch under .git/refs/remotes/origin.

I would presume the goal behind this design is to allow completely disconnected operation. If checkout -b were to attempt to base the new branch on the remote ref in the remote repository, the remote repository would have to be contacted. By storing the ref locally, the branch can still be created even when completely disconnected.