Search code examples
gitvcs-checkoutunstage

Git - How to recover code changes from file after accidentally git checkout particular file


I accidentally did checkout file. And that file had code changes.

So Can I recover that changes ?


Solution

  • Contrary to what people leaving comments would have you believe, a path-specific checkout (ie git checkout path/to/my/file) would indeed overwrite your unstaged changes in that file without warning, because that is exactly the command git expects you to use if you intend to undo unstaged changes.

    And unfortunately, because the changes were unstaged, git has no history of them. While git is very good at retaining history once it's been committed, it offers basically no special protection for the work tree; so commands affecting untracked files or files with unstaged changes are particularly dangerous.

    If you take continuous backups (or are lucky and took a backup while the changes existed), you could use those. Some IDE's keep a work history that might help. But unfortunately, in most cases (unless you have unusually solid backup practices) there probably isn't much to be done in this scenario.