If I run git branch -d XYZ
, is there a way to recover the branch? Is there a way to go back as if I didn't run the delete branch command?
A deleted Git branch can be restored at any time, regardless of when it was deleted. Open your repo on the web and select the Branches view. Search for the exact branch name using the Search all branches box in the upper right. Click the link to Search for exact match in deleted branches.
What Happens If I Delete a Git Branch? When you delete a branch in Git, you don't delete the commits themselves. That's right: The commits are still there, and you might be able to recover them.
I asked GitHub Support, this was their response (emphasis mine): We use a separate ref namespace for all Pull Requests which we use for various things including restoring the branch. Since we keep those [Pull Request] refs indefinitely, there's no time limit on restoring a branch.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With