Confusion over branch creation in git

After making a few changes to branch master I decided to work from a new branch. I did git checkout -b new_branch_name and a new branch was created and checked out. git status showed the changes I had made to master.

I was curious if my changes were now on both branches (master and new_branch_name) or just new_branch_name. So I checked out master and noticed my changes were there as well. So I reverted those changes with git checkout -- fileThatChanged. The changes were indeed gone from master.

Unfortunately checking out new_branch_name and running git status showed my changes were reverted from that branch as well.

I'd like to understand what happened and how can I avoid this in the future.

One solution is to just create/checkout a new branch before starting work.


You had never committed your changes to either branch. That is, if you did this:

$ git status

And saw something like this:

# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#   modified:   myfile.txt

The changes to "myfile.txt" do not "exist" on any branch -- they are only in your local working copy. They don't end up on a branch until you have comitted them to a repository.

If at this point I were to type:

$ git checkout myfile.txt

This would obliterate my changes (and return the file to whatever it looked like in the last commit on my current branch).

If I wanted to commit these changes on a new branch, I might do something like this:

$ git checkout -b new_branch_name
$ git add myfile.txt
$ git commit -m "made some changes"

Need Your Help

“Cannot find symbol” error in Java

java symbol jcreator

I've been programming for a few days, I'm using Deitel's How to program.

Creating constructor and send to view

c# ravendb

Im creating a pedigree-tree for my dogs and Im having som trouble.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.