← Recipes

阅读中文版本

Recover a Deleted Git Branch

Use the reflog to find the last commit of a deleted local branch and recreate the branch before garbage collection removes the commit.

~10 mingitrecoveryversion-control

Task

Recreate a branch that was deleted locally but whose commits still exist in the reflog.

When to use this

A feature branch was deleted with git branch -D or lost during a rebase. The work was not pushed and is not reachable from any current branch.

Prerequisites

  • The deletion happened on the same clone
  • The reflog has not expired (default 90 days for reachable entries, 30 for HEAD)
  • The repository has not run aggressive garbage collection since deletion

Steps

1. Inspect the reflog for the branch tip or the commit message you remember.

git reflog --date=iso | head -50

Expected output: A reflog entry showing the last commit of the deleted branch.

2. Create a new branch at the recovered commit. Use a descriptive name if the original is uncertain.

git branch recovered-feature <commit-sha>

Expected output: A new local branch points at the recovered commit.

3. Check out the branch and confirm the files and history are intact.

git switch recovered-feature && git log --oneline -5

Expected output: The expected commits and files are present.

4. Push the recovered branch immediately so it is no longer only in the reflog.

git push -u origin recovered-feature

Expected output: The remote branch exists and tracks the local branch.

Troubleshooting

Problem

The reflog has no entry

Solution

Check git fsck --lost-found for dangling commits, or recover from another clone, CI cache, or filesystem backup.

Problem

The commit is found but files are missing

Solution

Verify you selected the branch tip, not an intermediate commit; inspect git show --stat <sha>.

Limitations

  • Reflog data is local and expires; another machine cannot recover a branch that was never pushed.
  • Aggressive garbage collection can remove unreachable commits permanently.

How recovery works

Deleting a branch removes a reference, not the commits. Until garbage collection removes unreachable objects, the reflog still records where the branch pointed. Recreating the branch restores reachability.

git reflog --date=iso
# pick the commit that was the branch tip
git branch recovered-feature 9a1b2c3
git switch recovered-feature
git push -u origin recovered-feature

If the reflog is empty, look for dangling commits:

git fsck --lost-found
git show --stat <dangling-commit>

Verify

  • The recovered branch points at the expected commit.
  • git log --oneline shows the work you expected.
  • The branch is pushed to the remote, so a second loss is recoverable.
  • A test run or build passes on the recovered branch.

Prevention

Push feature branches early, even as drafts. Use git branch -d (which refuses to delete unmerged work) instead of -D unless you are certain. Remember that reflog recovery only works on the clone where the branch existed.