Recover from git reset --hard?

后端 未结 22 2522
盖世英雄少女心
盖世英雄少女心 2020-11-22 00:52

Is there any way to recover uncommitted changes to the working directory from a git reset --hard HEAD?

22条回答
  •  天涯浪人
    2020-11-22 01:41

    By definition, git reset --hard will throw away uncommitted changes without any way for Git to recover them (your backup system may help, but not Git).

    Actually, there are very few cases where git reset --hard is a good idea. In most cases, there's a safer command to do the same thing:

    • If you want to throw away your uncommitted changes, then use git stash. It will keep a backup of these changes, which will expire after some time if you run git gc. If you're 99.9% sure you'll never need these changes back, then git stash is still your friend for the 0.1% case. If you're 100% sure, then git stash is still your friend because these 100% have a measurement error ;-).

    • If you want to move your HEAD and the tip of the current branch in history, then git reset --keep is your friend. It will do the same thing as git reset --hard, but will not discard your local changes.

    • If you want to do both, then git stash && git reset --keep is your friend.

    Teach your fingers not to use git reset --hard, it will pay back one day.

提交回复
热议问题