Accidentally deleting a branch in Git can be stressful, but it’s often possible to recover it. Git keeps a log of all branch references, so you can restore a deleted branch if you act quickly. Below, we explain how to recover a deleted branch using Git commands and provide examples.

1. Recover a Deleted Branch Using Git Reflog

Git’s reflog (reference log) tracks all changes to the repository’s references, including branch deletions. You can use the reflog to find the commit where the branch was last active and recreate the branch from that commit.

Steps to Recover a Deleted Branch

  1. Check the reflog: Use git reflog to view the history of changes.

  2. git reflog
  3. Find the deleted branch: Look for the commit where the branch was last active. The log entry will include the branch name and the commit hash.

  4. abc123 HEAD@{0}: checkout: moving from feature/old-branch to main
    def456 HEAD@{1}: commit: Add new feature
  5. Recreate the branch: Use the commit hash to recreate the branch.

  6. git checkout -b feature/old-branch def456

2. Recover a Deleted Branch from a Remote Repository

If the branch was pushed to a remote repository before it was deleted, you can recover it by checking out the branch from the remote.

Steps to Recover from a Remote Repository

  1. Fetch the remote branches: Use git fetch to update your local repository with the remote branches.

  2. git fetch origin
  3. Check out the deleted branch: Use git checkout to recreate the branch from the remote.

  4. git checkout -b feature/old-branch origin/feature/old-branch

3. Recover a Deleted Branch Using Git fsck

If the branch was deleted locally and not pushed to a remote, you can use git fsck to find dangling commits and recreate the branch.

Steps to Recover Using Git fsck

  1. Run git fsck: Use git fsck to find dangling commits.

  2. git fsck --lost-found
  3. Identify the commit: Look for the commit associated with the deleted branch.

  4. dangling commit abc123
  5. Recreate the branch: Use the commit hash to recreate the branch.

  6. git checkout -b feature/old-branch abc123

4. Prevent Branch Deletion

To avoid accidentally deleting branches, you can protect important branches using Git’s branch protection features or by setting up hooks.

Example of Protecting a Branch


# Prevent deletion of the main branch
git config --global branch.main.protect true

Conclusion

Recovering a deleted branch in Git is possible using tools like reflog, remote repositories, or fsck. By understanding these methods, you can quickly restore lost work and avoid disruptions to your workflow. Additionally, protecting important branches can help prevent accidental deletions in the future.