Cyker
Cyker

Reputation: 10914

Git: git checkout with modified working tree and index

I expect git checkout <commit> to flash both the working tree and index to the <commit> version. However, in some cases it will keep the current changes in both the working tree and index. For example:

git branch br1
git branch br2
git checkout br1
<make change M1 to file foo>
git add foo
<make change M2 to file foo>
git checkout br2

Now all the working tree/index changes made in branch br1 are kept in the branch br2, as git status on br2 won't give a clean message. I guess this is because the head of br1 and br2 originally have the same version of file foo, and Git can automatically detect this.

Question:

Upvotes: 5

Views: 2296

Answers (1)

Dietrich Epp
Dietrich Epp

Reputation: 213338

The git checkout command actually has two different (common) operating modes.

  1. If you run git checkout <branch>, then you will switch to branch <branch>. All changes to the working tree will be kept -- and this works by merging the uncommitted changes to the target branch, so it can fail. Changes in the index will be stashed.

  2. If you run git checkout <path>, then git will wipe out the changes to <path> in both the index and the working copy by getting them from the current commit.

So the purpose of git checkout <branch> is in case you decide that the changes you're making actually belong on a different branch.

Upvotes: 6

Related Questions