Skip to main content
Git’s built-in history tracking and reflog functionality serve as a powerful “time machine” for your repository. In this guide, you’ll learn how to:
  • Restore deleted commits
  • Undo recent commits
  • Recover deleted branches
These techniques help you safely navigate and recover from mistakes in your Git workflow.

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.
This displays a chronological list of all HEAD movements. Locate the desired commit hash in the reflog output.
You’re now in a “detached HEAD” state. To preserve this commit on a branch:
This creates a new branch named 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, use git reset. Choose between a soft or hard reset based on whether you need to preserve your worktree and index.

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.
For more on reset modes, see Git Reset Documentation.

3. Recovering a Deleted Branch

Accidentally deleted a branch? You can bring it back if its commits still exist in the reflog.
  1. View the reflog:
  2. Find the commit hash where your branch last pointed.
  3. Recreate the branch:
Your deleted branch is now restored, complete with its history.

Watch Video