Home > database >  Checkout another branch and not commit the code, can I get the code before checkout
Checkout another branch and not commit the code, can I get the code before checkout

Time:09-30

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?

CodePudding user response:

Unless you did a reset first the changes should still be there.

CodePudding user response:

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 branch A,
  • and file foo.txt exists and is versioned in branch B,

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.

  •  Tags:  
  • git
  • Related