DEV Community


How to restore (recreated) a deleted remote git branch

mreigen profile image mreigen Originally published at Medium Updated on ・2 min read

I ran into this when I was cleaning up my local git. I deleted both a local and its remote branch on origin! 🤦‍♂ And the branch I deleted is still in a Merge (Pull) Request! 💀 I used a third party app called SourceTree (I’m sure you heard of it) to delete them, so my commit is not in the reflog

What I did to restore the local branch is as follow:

  • Since my commit is not in the reflog, I had to do this to print out and ultimately find my commit’s sha

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

  • I could open this file with my editor to find the sha by my commit message (I was glad I remembered some key words in it) and made sure if the changes are what I did:

git log -p <sha>

  • Finally, I recreated the deleted branch by doing:

git branch hotfix-whatever-branch <sha>

All I did to do after this is to push the branch and voila, the branch was restored successfully!

What I learned from this syntax:

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

--git fsck: file system check. It verifies the connectivity and validity of the objects in the database

-no-reflogs Do not consider commits that are referenced only by an entry in a reflog to be reachable. This option is meant only to search for commits that used to be in a ref, but now aren’t, but are still in that corresponding reflog

--unreachable: Print out objects that exist but that aren’t reachable from any of the reference nodes.

--full Check not just objects in GIT_OBJECT_DIRECTORY ($GIT_DIR/objects), but also the ones found in alternate object pools listed in GIT_ALTERNATE_OBJECT_DIRECTORIES or $GIT_DIR/objects/info/alternates, and in packed Git archives found in $GIT_DIR/objects/pack and corresponding pack subdirectories in alternate object pools. This is now default; you can turn it off with --no-full.

--lost-found Write dangling objects into .git/lost-found/commit/ or .git/lost-found/other/, depending on type. If the object is a blob, the contents are written into the file, rather than its object name.

You can see the full documentations here:

The rest of the pipeline is to pick the info we need, format it and send it to a file.

The Linux cut command

Discussion (0)

Editor guide