Can I recover a branch after its deletion in Git?

When your commits are in the reflog

Most of the time unreachable commits are in the reflog. So, the first thing to try is to look at the reflog using the command git reflog (which displays the reflog for HEAD).

Perhaps something easier is to use the command git reflog name-of-my-branch if the commit was part of a specific and still existing branch. It also works with a remote e.g. if you had force pushed (though one should use git push --force-with-lease instead which prevents mistakes and is more recoverable).


When they aren't in the reflog

If your commits are not in your reflog (perhaps they were deleted by a 3rd party tool that doesn't write to the reflog), you may try this command first to create a file with all the dangling commits

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

then read the SHA of the missing commit and reset you branch to it.

Frequent users may create the alias git rescue using

git config --global alias.rescue '!git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt'

Here are some examples showing how to analyze the found commits

Display commit metadata (author, creation date and commit message):

git cat-file -p 48540dfa438ad8e442b18e57a5a255c0ecad0560

Also see diffs:

git log -p 48540dfa438ad8e442b18e57a5a255c0ecad0560

Create a branch on the found commit:

git branch commit_rescued 48540dfa438ad8e442b18e57a5a255c0ecad0560

Windows GUIs can easily recover commits (also uncommitted staged files) with GitExtensions via the menu Repository => Git maintenance => Recover lost objects...

Related: Easily recover deleted files that have been staged previously


Yes, you should be able to do git reflog --no-abbrev and find the SHA1 for the commit at the tip of your deleted branch, then just git checkout [sha]. And once you're at that commit, you can just git checkout -b [branchname] to recreate the branch from there.


Credit to @Cascabel for this condensed/one-liner version and @Snowcrash for how to obtain the sha.

If you've just deleted the branch you'll see something like this in your terminal Deleted branch <your-branch> (was <sha>). Then just use that <sha> in this one-liner:

git checkout -b <your-branch> <sha>