git,

The proper way to restore a deleted Git branch

Sep 19, 2022 · 1 min read · Post a comment

Personally, not a huge fan of switching between branches and complicating things as much as they need to. Therefore, the trunk-based development must be the most perfect Git branching strategy, though most of us are lazy and want to commit things directly into the main branch (I know you would!). To not get off topic, today’s post is going to be all about recovering Git branches.

Prerequisites

  • Git

Solution

If you already know the branch SHA1 from the tip (the last commit), you could try to run:

git checkout -b <branch-name> <commit-SHA1>

If that not the case, list all Git commits first and find the tip of the deleted branch:

git log
git checkout -b <branch-name> <commit-SHA1>

Last but not least, in case you are still having trouble finding the right commit, run:

git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > temp

Find the commit first, then show the commit details just to be sure that’s the one:

git show <commit-SHA1>

As with recovering deleted remote branches, every Git-hosted platform has its own docs.

Conclusion

List of related posts:

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git