I checkout another branch (branch2) and forget to commit the code (in branch1), when I checkout this branch (branch1) again the code have lost. How can I get the code before checkout?
-
1By default git [won't let you switch branches when that would overwrite uncommited changes](https://stackoverflow.com/questions/22712166/switching-branches-in-git-with-working-directory-not-clean). What have you done to still be able to? – Joachim Sauer Sep 29 '21 at 10:37
-
Chances are your changes are really gone and git can't help you get it back. But if you use an IDE with a "local history" feature (such as all IntelliJ based IDEs like IDEA) then you might be able to find your changes in there. – Joachim Sauer Sep 29 '21 at 10:38
-
1Does this answer your question? [git checkout branch after git add, seems not update index and working area](https://stackoverflow.com/questions/67450004/git-checkout-branch-after-git-add-seems-not-update-index-and-working-area) – matt Sep 29 '21 at 10:44
-
Thanks @JoachimSauer, I use Android Studio and the old code still have in Local History – tiennl Sep 29 '21 at 10:48
-
1https://stackoverflow.com/questions/68320608/changing-branches-does-not-discard-local-changes – matt Sep 29 '21 at 10:49
-
2Don't put Solved in the title. If the problem is solved, accept an answer, give a different answer, or delete the question. – matt Sep 29 '21 at 11:05
2 Answers
There is at least one situation, where git
will silently "forget" the changes in a staged file when you change branches : when the staged file has exactly the same content as the file in the target branch.
In that case, git
will allow you to switch branches, and will keep the same content for that file -- which therefore will not appear as modified anymore.
If you want to switch back to your original branch, the burden falls on you to identify what files should be taken back from that other branch ; but at least, they should have the content you expect.
This is a reason why you will see recommendations to commit your changes, or at least stash them away (using git stash
) before changing branches.
There is another corner case, which may mess with the content of files on your disk when switching branches :
- if file
foo.txt
is ignored (by a.gitignore
rule) on branchA
, - and file
foo.txt
exists and is versioned in branchB
,
then switching to branch B
from branch A
will silently replace the content of foo.txt
with its versioned content (tested with git 2.33
, this happens with both git checkout
and git switch
).
I haven't read the code for other possible corner cases, testing some basic cases on my machine indicate that git
doesn't try anything more complex ; if there are any other kind of modifications to a file, git checkout
or git switch
should error with an explicit message.

- 46,477
- 5
- 57
- 104