Is it ever possible to lose work in git? Let's assume all my work is committed, and I didn't run git gc
.
If I try some "funky command" ( NOT rm -rf .git
), and something strange happens to my project, could I recover from it?
Is there something in particular I should avoid doing? Or clone the repository elsewhere before attempting it?
To remove the last commit from git, you can simply run git reset --hard HEAD^ If you are removing multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits. You can increase the number to remove even more commits.
You can simply remove that commit using option "d" or Removing a line that has your commit. In the latest git version there is no more option d. You need just remove lines with commits from rebase to delete them.
In order to undo the last Git commit, keep changes in the working directory but NOT in the index, you have to use the “git reset” command with the “–mixed” option.
(drop) — If you remove a commit from the interactive rebase file, or if you comment it out, the commit will simply disappear as if it had never been checked in. Note that this can cause merge conflicts if any of the later commits in the branch depended on those changes.
Most errors you make with git can be recovered through the use of the reflog. One exception to this is deleting your branch, because of course that deletes the associated reflog. If that happens you may still be able to find the branch again by looking at the reflog of HEAD, but if you haven't checked the branch out in a while (or never checked out the latest tip of the branch) then it won't be there. But even then, you can try using git fsck --lost-found
to find your dangling commits, and trawl through them to find likely candidates for the branch tip.
As you already indicated, if you run something which corrupts the .git
directory, then all bets are off.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With