简体   繁体   中英

Git: When creating a new branch without commit, changes to master changes branch too

Let's say I have a brand new project with a text file. I run:

git init

git add *

git commit -m 'Initial commit'

Then create a new branch:

git checkout -b new_branch

Go back to master:

git checkout master

If I now change my text file, and then, without committing, run:

git checkout new_branch

The file in new_branch is also changed! Why is this? They're both pointing to the same commit (same hash), but it still feels counterintuitive that changes on master also changes new_branch . Is my understanding of git flawed when I expect new_branch to be the same as when it was created?

(PS: I'm not asking for how to create a new branch or how to save my work using a branch, I'm just puzzled by gits behaviour in this specific circumstance, and want to understand its logic better)

Because your changes are in the working directory/staging area, so they aren't committed. And when you check something else out they will be carried over unless a conflict when the checkout will be aborted. Very convenient.

Git is smart enough to not throw away uncommited changes. As long as there are no conflict, it will move the delta to whichever branch you change to. This is handy if you ever accidently start making changes on the wrong branch.

it still feels counterintuitive that changes on master also changes new_branch

You only changed a file in the working tree, you didn't change master yet. You change the data in the repository when you git commit .

Let's take a look at what the documentation says:

git checkout <branch>

To prepare for working on <branch> , switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the <branch> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM