开发者

Why does git merge changes automatically when i switch branches?

开发者 https://www.devze.com 2023-01-12 05:51 出处:网络
I\'m new to branching in git and I\'m a bit confused by the behaviour on swithing branches. Following these steps:

I'm new to branching in git and I'm a bit confused by the behaviour on swithing branches. Following these steps:

git init
Initialized empty Git repository in /Users/mads/Desktop/testing/.git/

echo 'hello a' > a.txt
echo 'hello b' > b.txt
git add *.txt
git commit -m "Initial commit"
[master (root-commit) 1ab870f] Initial commit
 2 files changed, 2 insertions(+), 0 deletions(-)
 create mode 100644 a.txt
 create mode 100644 b.txt

git status
# On branch master
nothing to commit (working directory clean)

git branch new_feature
git checkout new_feature
Switched to branch 'new_feature'

ls
a.txt   b.txt

echo "hello c" > c.txt
git add c.txt 

echo "hello a, new version" > a.txt

git status
# On branch new_feature
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   c.txt
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   a.txt
#

git commit -m "Added new feature"

[new_feature 1ccda31] Added new feature
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 c.txt

git checkout master
M   a.txt
Switched to branch 'master'

cat a.txt 
hello a, new version

Why does changes on a.txt get pulled into master automatically on checkout? Isn't this the purpose of 'merge'? I thought working on a branch and 开发者_如何学Cthen switching to another one would be isolated...


You never ran git add a.txt after modifying it. Git doesn't automatically track the changes you make to files, even to files you've already added to the repository. (This is different from SVN, for instance) You have to explicitly git add each file each time you change it, if you want the changes to be versioned.

Alternatively, you can use the -a option to git commit, which will automatically add and commit any changes made to files which git is already tracking. So the closest thing to svn commit would be git commit -a.


You didn't add a.txt to your commit, so it's still a modified working file. When you checkout master it doesn't want to overwrite your changes so the change to a.txt still exists in your working directory.


The problem you are having is that the change to was not committed.

That's what the M a.txt means when you checked out master again.

If you do commit -a instead of just the commit it will commit all changed files. Alternatively you have to add all changed files you want to commit.

If everything is properly committed you will see that the branches are well isolated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号