- Restore deleted commits
- Undo recent commits
- Recover deleted branches
1. Restoring a Deleted Commit
When a commit disappears (e.g., via a force-push or a branch deletion), Git’s reflog can track its SHA-1 hash.HEAD movements. Locate the desired commit hash in the reflog output.
restore-branch pointing at the recovered commit.
By default, Git keeps reflog entries for 90 days. If you don’t find your commit, it may have been pruned. Configure retention with
gc.reflogExpire.2. Undoing the Last Commit
If you simply want to undo the very last commit on your current branch, usegit reset. Choose between a soft or hard reset based on whether you need to preserve your worktree and index.
| Reset Type | Description | Command |
|---|---|---|
| Soft | Undo commit, keep changes staged | git reset --soft HEAD~1 |
| Mixed | Undo commit, unstage changes (default behavior) | git reset HEAD~1 |
| Hard | Undo commit and discard staged & working changes | git reset --hard HEAD~1 |
2.1 Soft Reset
- Moves the branch pointer back by one commit.
- Leaves your working directory and index untouched.
2.2 Hard Reset
- Moves the branch pointer back by one commit.
- Resets both your index and working directory to the new
HEAD.
git reset --hard irreversibly discards all uncommitted changes. Make sure you really want to lose those changes.3. Recovering a Deleted Branch
Accidentally deleted a branch? You can bring it back if its commits still exist in the reflog.-
View the reflog:
- Find the commit hash where your branch last pointed.
-
Recreate the branch: