gitgit-checkoutfile-recovery

Undo git checkout --


I first checkout a branch from feature branch.

git checkout -b MyBranch

Made some changes in that branch. Added all the files. Then I moved to feature branch. All my staged changes are present in feature branch. Then I did:

git checkout -- <Staged File>

I then moved to my branch. I dont see my staged file in MyBranch.

Is there any way I could recover my staged file ?


Solution

  • Unfortunately your uncommitted changes to the file are lost, if I understand your situation correctly.

    The command git checkout -- [file] reverts any uncommitted changes made to a file. It changes its version to that of the last commit on the current branch.

    You say that you don't see the file anymore. Unless the file does not exist in the latest commit of your branch, that is weird (and you should read this answer). But if you're positive it exists on the remote branch, there's a way to get it back:

    git checkout HEAD -- [file]
    

    This resets the file's version as well as its state in the index.

    Preventing this in the future

    So you have some changes to files, but want to apply them on a different branch or commit before making a commit. For this you can use [git stash][1]. As the docs put it:

    Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory.

    In your case that would mean:

    1. Make changes to files
    2. Add the files: git add [your-files-or-parameter]
    3. Stash the files: git stash
    4. Switch to feature branch: git checkout [feature-branch]
    5. Apply your stashed changes: git stash apply

    Now your changes are applied on top of the feature branch state.

    Note that git stash apply leaves the stash record in the stash index, which means that after you apply it, it's still stashed there. You can use git stash pop to apply and remove the stash, but I find it useful that you're able to reset and redo the switching without losing your changes if something goes wrong.