32

It seems that I delete a branch on github when I should not do it.

What I did was as follow:

1- I add a new .gitignore to my system

2- I use

 git rm -r --cached .  
 git add .  
 git commit -m ".gitignore is now working"  

When I did this, I had one branch on my local system but the server had two branch.

Then I pushed my branches to server and since I had not the second branch, the second branch was deleted on server.

How can I bring it back?

I am using Github as remote server.

mans
  • 17,104
  • 45
  • 172
  • 321
  • how did you pushed your branches? – sites May 06 '13 at 12:24
  • @juanpastas: I am using git from inside VS and I used git > push > push multiple branches and I select the branch that I had not on my local repository – mans May 06 '13 at 12:26
  • *push. See http://stackoverflow.com/questions/1992364/git-recover-deleted-remote-branch – sites May 06 '13 at 12:33
  • checkout this link http://blog.blazingcloud.net/2012/07/05/undelete-a-branch-in-git/ – shrikant1712 May 06 '13 at 12:50
  • FYI if you delete a branch on GitHub's web UI, you can easily restore it: https://help.github.com/articles/viewing-branches-in-your-repository/#deleting-branches – Dennis Dec 31 '15 at 13:58

4 Answers4

80

If you know the last commit message of the deleted branch you can do this:

git reflog

# search for message

fd0e4da HEAD@{14}: commit: This is the commit message I want

# checkout revision

git checkout fd0e4da 

or

git checkout HEAD@{14}

# create branch

git branch my-recovered-branch

# push branch

git push origin my-recovered-branch:my-recovered-branch
Sayan Paul
  • 91
  • 1
  • 13
sites
  • 21,417
  • 17
  • 87
  • 146
19

If this branch was deleted during the Pull Request, you can undo that right there in the UI using the "restore branch" button.

Tricky part is actually finding a PR that has been merged and closed, you just need to know the URL or the PR number to put into the URL. You can try looking in your deleted notification emails or just guess the PR number.

Writing this cause reflog didn't help me restoring a teammate commit to a branch I've never pulled on my local git.

Brock
  • 1,635
  • 2
  • 18
  • 27
4

what if you git fetch remote && git checkout -b remote_branch_name

Luiz E.
  • 6,769
  • 10
  • 58
  • 98
  • 1
    Thanks, but it doesn't work: $ git fetch remote fatal: 'remote' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. – mans May 06 '13 at 12:23
  • 2
    `remote` is the name of your remote repo (GitHub in this case). try `git remote list` to see the name of your remote repo (I think that is `origin`) and use that name instead of `remote` – Luiz E. May 06 '13 at 12:24
0

Inside github.com you can restore it after the fact by Pull requests, open the last request and you should see a Recover/Restore branch button

cire
  • 124
  • 1
  • 9