0

Let's say that I am on master branch, and I have 1 file temp.py and 1 commit, then

1) I made a change to temp.py

2) checkout another branch (feature)(I don't add or commit the file)

3) On feature branch, I add temp.py and commit changes

4) checkout master again, the original change that I made to temp.py is undone

Here is the code that does the above steps:

$ git branch
* master
$ cat temp.py
print "Hello World"
$ echo "print \"Bye Bye\"" >> temp.py
$ cat temp.py
print "Hello World"
print "Bye Bye"
$ git checkout -b feature
M   temp.py
Switched to a new branch 'feature'
$ git add temp.py
$ git commit -am "added Bye Bye to temp.py"
[feature d8e363a] added Bye Bye to temp.py
 1 file changed, 1 insertion(+)
$ git checkout master
Switched to branch 'master'
$ cat temp.py
print "Hello World"
$

Before add and commit on feature branch, temp.py on master was:

print "Hello World"
print "Bye Bye"

But after add and commit on feature, the change was undone, and I ended with:

print "Hello World"

I am puzzled as to why committing changes on feature branch affects master branch, why is this happening?

I know that this example is not normal usage of git, but I feel like it underlines some aspects of git that I don't understand.

This question is related to what I am asking: Checkout another branch when there are uncommitted changes on the current branch, but I was not able find answer to my question there.

Akavall
  • 82,592
  • 51
  • 207
  • 251

1 Answers1

3

This looks correct to me. Here's where you may be confused.

When you checked out a new branch, Git preserved your working index and brought it along with you to the new branch. You can see this from this line:

M   temp.py

Right now, that copy of temp.py is the only one Git is aware of with the two lines.

When you committed this change, feature now contains the Python file with the two lines in it. Now you've changed back to master and, as expected, master only contains one line.

You didn't commit your changes to master, so master has no working knowledge of these changes. They exist on your feature branch instead.

Makoto
  • 104,088
  • 27
  • 192
  • 230