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

后端 未结 2 826
清酒与你
清酒与你 2021-02-14 23:06

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 br

相关标签:
2条回答
  • 2021-02-14 23:36

    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.

    0 讨论(0)
  • 2021-02-14 23:49

    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

    0 讨论(0)
提交回复
热议问题