Sahil
Sahil

Reputation: 9480

Why does uncommitted change in a branch affect the master branch?

I am new to git and I am trying to experiment with it to understand the concepts particularly the branching and merging.

So here is my set up,

I have a master branch, I create a master text file with 'master' text.
Now I do git checkout -b branch and create a branch.
I edit the branch 'parent' file and add one line of text.

Now If I commit this change and switch back to master, It won't affect as It shouldn't, as Branch changes should not reflect in the master branch.

However If I leave the branch uncommitted and switch to master, This change reflect there and git treats master file as edited, When I do

git status -s

It shows that master file with M.

Can anyone explain to me how the uncommitted changes are reflecting in the master branch?

Upvotes: 13

Views: 9053

Answers (2)

CharlesB
CharlesB

Reputation: 90316

Git keeps your uncommitted changes when checking out another branch, which is very practical.

You can see this as uncommitted changes "belong" only to your working copy, and not to any branch or commit. They are independent. When you will commit the changes in a branch, they will of course change if the checkout has a different version for the file.

The only exception to this behaviour is if the branch change brings an uncommitted file to a different version, it which case the checkout is canceled:

A--B - feature
 \
  -C - master

Let's say commit B in the feature branch changes a line to foo.txt, and that you have the master branch checked out. You have made a different change to foo.txt.

  1. You commit the change in master and checkout feature

    git add foo.txt
    git commit -m "changed foo.txt"
    git checkout feature
    

    Here no problem, the change is recorded in master and when you go to feature foo.txt is changed accordingly.

  2. If you don't commit and try to checkout feature, then Git will print an appropriate message, and keep the master branch checked out:

    git checkout feature
    

    error: Your local changes to the following files would be overwritten by checkout:
    foo.txt
    Please, commit your changes or stash them before you can switch branches. Aborting

Upvotes: 9

Anuj Aneja
Anuj Aneja

Reputation: 1344

In Git or any version control system all the merge operations are to be done on the local machine itself. So, if you have any uncommitted changes on any branch so that they don't get lose/unnoticed they are merged with branch just switched/new checkout. Your changes will always be there unless you use git push. Ofcourse, there could have been a reverse case as well, but it is often more beneficial for the programmer.

Upvotes: 0

Related Questions