1519

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 10
    A really awesome note to make about the accepted answer is that it works even if the branch was deleted in origin! I just recovered several branches that I did not have locally anymore after they were accidentally deleted in origin. – theblang May 21 '18 at 21:35

24 Answers24

2787

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>
Brady Dowling
  • 4,920
  • 3
  • 32
  • 62
tfe
  • 32,666
  • 2
  • 27
  • 24
  • 18
    For any folks who did the deletion from SourceTree rather than command line, you can find out your SHA1 by going to View -> Show Command History. Find the Deleting branch command and look for the "Deleted branch (was )" message. – Nobosi Sep 26 '18 at 19:17
  • 1
    For GitKraken: take a look at the Activity Log and you should see an entry like this: `Delete ref at : finished.` – starikcetin Feb 20 '21 at 00:06
  • Once I've done `git checkout [sha]`, git suggested me to do ` git switch -c ` ... I think that it does the same of `git checkout -b ` ... maybe it's a new command?! – funder7 Jan 19 '22 at 00:35
  • @funder7 `git switch` has been a thing for a few years :P "switch to this branch, creating before switching" – Momo Jan 24 '22 at 23:00
  • Oh...okay! :-D I'll try to remember this command, I'm too accustomed to checkout -b! – funder7 Jan 25 '22 at 09:12
  • 2
    I wanted to rename `master` into `main` then merge changes from `dev` . My `dev` branch was automatically deleted because of renaming `master` to `dev` by mistake (because an existing branch already had this name). This solved my issue. – Karobwe Mar 02 '22 at 09:19
  • This really saved my bacon. – Darko Dec 27 '22 at 20:57
  • Can someone accidentally delete the main branch? I'm deleting completed branches and I see the option to delete 'origin/main" or "origin/master". – 1.21 gigawatts Feb 21 '23 at 20:29
  • I was having heart issues till I found this answer. My heart is fine now. – xleon May 11 '23 at 16:01
269

(Re)Creating the branch ONCE you've got the commit hash

Here is the command to create the new branch:

git branch <my-new-branch-name> <commit-hash>

So you will have to find the commit hash and you will have 2 options explained just below:


Finding commit hash with the command line

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 are NOT 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

Using GitExtensions GUI on Windows

Similarly to what you can do from the command line, you can take the commit hash from the reflog or from dangling commits:

From the reflog

You have 2 options:

  • Display dangling commits in the revision grid (maybe the easiest): In the menu View => Show reflog references and you should now be able see the dangling commits present in the reflogs Reflog displayed in revision grid
  • Access to reflog content for HEAD or another branch: In the menu Commands => Show reflogs... reflogs

Finding the commit not in the reflog

You can easily recover lost commits ( and also uncommitted staged files!) with via the menu Repository => Git maintenance => Recover lost objects.... For each commit, sorted by date, you will have the hash, the commit message and will be able to display easily the commit diff. Recover lost commits

Related: Easily recover deleted files that have been staged previously

Philippe
  • 28,207
  • 6
  • 54
  • 78
65

If you like to use a GUI, you can perform the entire operation with gitk.

gitk --reflog

This will allow you to see the branch's commit history as if the branch hadn't been deleted. Now simply right click on the most recent commit to the branch and select the menu option Create new branch.

Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
  • 1
    Thank you, I did not know about that one. When you deleted the branch a few days ago, haven't checked it out for a couple of weeks, don't remember what it was called and don't have the shell history... this saved my ass. – Gordon Wrigley Aug 28 '20 at 12:45
  • 1
    thank you so much i almsot lost week of work – urek mazino Mar 05 '23 at 19:36
37

The top voted solution does actually more than requested:

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

or

git checkout -b <branch> <sha>

move you to the new branch together with all recent changes you might have forgot to commit. This may not be your intention, especially when in the "panic mode" after losing the branch.

A cleaner (and simpler) solution seems to be the one-liner (after you found the <sha> with git reflog):

git branch <branch> <sha>

Now neither your current branch nor uncommited changes are affected. Instead only a new branch will be created all the way up to the <sha>.

If it is not the tip, it'll still work and you get a shorter branch, then you can retry with new <sha> and new branch name until you get it right.

Finally you can rename the successfully restored branch into what it was named or anything else:

git branch -m <restored branch> <final branch>

Needless to say, the key to success was to find the right commit <sha>, so name your commits wisely :)

Dmitri Zaitsev
  • 13,548
  • 11
  • 76
  • 110
31

If you removed the branch and forgot its commit id, you can do this command:

git log --graph --decorate $(git rev-list -g --all)

After this, you'll be able to see all commits. Then, you can do git checkout to this id and under this commit create a new branch.

Pang
  • 9,564
  • 146
  • 81
  • 122
borkafight
  • 487
  • 1
  • 5
  • 10
  • 1
    This one allowed me to recover a couple year-old branches that none of the other methods could find. Thanks! – Beer Me Dec 01 '21 at 18:39
  • I've tried your command and I get a list of commits within the branch, but I want to restore the deleted branch, how can I do it? – Mike May 21 '22 at 18:42
19

First type

git reflog

in the terminal.

After that, get the HEAD@{**number**} (e.g. HEAD@{12}).

Now enter:

git checkout -b 'branch_name' 'HEAD@{22}'
buddemat
  • 4,552
  • 14
  • 29
  • 49
Debbie Maciel
  • 186
  • 1
  • 6
16

Adding to tfe answer: there is also the git-resurrect.sh script in the contrib/ area of the Git sources (in git.git repository), which might help you.

git-resurrect <name> attempts to find traces of a branch tip called <name>, and tries to resurrect it. Currently, the reflog is searched for checkout messages, and with -r also merge messages. With -m and -t, the history of all refs is scanned for Merge <name> into other/Merge <other> into <name> (respectively) commit subjects, which is rather slow but allows you to resurrect other people's topic branches.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jakub Narębski
  • 309,089
  • 65
  • 217
  • 230
  • 1
    It worked for me now although I had to add /usr/lib/git-core/ to my PATH . But it didn't perform the miracle I was hoping for :( – AmanicA Nov 27 '15 at 04:59
14

I used the following commands to find and retrieve my deleted branch. The first steps are from gcb's description.

$ git fsck --full --no-reflogs --unreachable --lost-found > lost
$ cat lost | cut -d\  -f3 > commits
$ cat commits | xargs -n 1 git log -n 1 --pretty=oneline

Now look for the git commit id (GIT-SHA) based on the commit comments and use it in the command below. Checkout a new branch called NEW-BRANCH with the previously found GIT-SHA:

$ git checkout -b NEW-BRANCH GIT-SHA
Patrick Koorevaar
  • 1,219
  • 15
  • 24
  • Thank you very much. Took a little time to search the name, but the time worth it. If there is a way to also search on commit message string, would be much better. – Monir Khan Feb 28 '20 at 14:53
  • I have same problem with the question posted above, and this answer works for me. – ira Nov 30 '21 at 23:57
10

From my understanding if the branch to be deleted can be reached by another branch, you can delete it safely using

git branch -d [branch]

and your work is not lost. Remember that a branch is not a snapshot, but a pointer to one. So when you delete a branch you delete a pointer.

You won't even lose work if you delete a branch which cannot be reached by another one. Of course it won't be as easy as checking out the commit hash, but you can still do it. That's why Git is unable to delete a branch which cannot be reached by using -d. Instead you have to use

git branch -D [branch]

This is part of a must watch video from Scott Chacon about Git. Check minute 58:00 when he talks about branches and how delete them.

Introduction to Git with Scott Chacon of GitHub

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fabiopagoti
  • 1,467
  • 14
  • 31
  • 9
    How is this helping to answer the question? – Dmitri Zaitsev Apr 28 '15 at 13:36
  • 11
    Telling the asker that branches don't hold content but are actually pointers. You don't need to be afraid of deleting branches.. you can create new ones pointing to the same commit as the deleted one.... Wow! I still remember when I askered this question. Good times back to 2012! – fabiopagoti Apr 28 '15 at 19:04
  • 4
    Had to scroll three screens to AT LAST find an answer who adresses the problem : deleting a branch is deleting a mere pointer. No data loss situation here, the only thing to recover is where was it pointing. Answers who go directly to `reflog` are just overkill. – Romain Valeri Jan 18 '19 at 19:38
  • @RomainValeri : great, so how do you recover `branch_name` without using `reflog`? – eric Jun 02 '23 at 19:17
9

If you don't have a reflog, eg. because you're working in a bare repository which does not have the reflog enabled and the commit you want to recover was created recently, another option is to find recently created commit objects and look through them.

From inside the .git/objects directory run:

find . -ctime -12h -type f | sed 's/[./]//g' | git cat-file --batch-check | grep commit

This finds all objects (commits, files, tags etc.) created in the last 12 hours and filters them to show only commits. Checking these is then a quick process.

I'd try the git-ressurect.sh script mentioned in Jakub's answer first though.

Community
  • 1
  • 1
Robert Knight
  • 2,888
  • 27
  • 21
  • 1
    Nice alternative idea! Your command throws an error though. The problem is with the "12h" part (actually the "h"). Once I removed the "h" it worked alright. From `man find`: "-ctime n - File's status was last changed n*24 hours ago." So we should also change 12 to 0.5 to have the expected behaviour of last 12 hours. – pagliuca May 15 '13 at 12:23
  • 1
    I'm using OS X 10.8 here, so the 'find' flags above are based on the version that it ships. – Robert Knight May 15 '13 at 13:13
  • 1
    Yeah, sure the problem is with versions! That's why I upvoted your answer at first place! I just commented so people realize parameters might be different. – pagliuca May 15 '13 at 17:29
9

For GitHub users without Git installed:

If you want to restore it from GitHub website, you can use their API to get a list of repo-related events:

First

  • find those SHAs (commit hashes):

    curl -i https://api.github.com/repos/PublicUser/PublicRepo/events

    ... or for private repos:

    curl -su YourUserName https://api.github.com/repos/YourUserName/YourProject/events

    (will be prompted for GitHub password)

    • (If the repo rquires two-factor auth, see the comments on this answer below.)

Next

  • go to GitHub and create a new temporary branch which will be deleted for ever (Chrome is preferable).

   •  Go to branches and delete that one.

   •  On the same page, without reloading, open DevTools, Network panel. Now prepare...

   •  Click restore. You will notice a new "line". Right-click on it and select "Copy as cURL" and save this text in some editor.

   •  Append to the end of the copied line of code, this one: -H "Cookie=".

You should now get something like:

    curl 'https://github.com/UserName/ProjectName/branches?branch=BranchSHA&name=BranchName' -H 'Cookie:' -H 'Origin: https://github.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US' -H 'User-Agent: User-Agent' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: */*' -H 'Referer: https://github.com/UserName/ProjectName/branches' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --data 'utf8=%E2%9C%93&authenticity_token=token' --compressed

Final step

  • replace "BranchSHA" with your SHA-hash and BranchName with desired name (BTW, it is great hack to rename branch from web). If you were not too slow, you need to make this request anyhow. For example, just copy-paste to a terminal.

P.S.

I realize this may not be the "simplest solution" or the "right" solution, but it is offered in case someone finds it useful.

TT--
  • 2,956
  • 1
  • 27
  • 46
Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
  • 1
    The above is one of the few out there that doesn't rely on `git reflog` and therefore was useful for example when having deleted a remote branch and lost access to the computer that was done from so nothing useful cold be obtained from `reflog`. Note when [using OAuth or two-factor authentication on Github](https://developer.github.com/v3/auth/#via-oauth-tokens) the `curl` command becomes of the form: `curl -u username:token https://api.github.com/user` or `curl -H "Authorization: token TOKEN" https://api.github.com/repos/USER_OR_ORG_NAME/REPO_NAME/events` – TT-- Apr 18 '19 at 17:25
  • @TT-- wow, I'm glad it helped! and thanks for your contribution regarding auth token :) – Maxim Mazurok Apr 19 '19 at 12:06
9

Thanks for all of you.

My problem was that i deleted my branch on GitLab (remotely) as well as on GIT (locally).

but somehow i got my commits back like so:

  1. first i got the last commit (SHA) with
git log --graph --decorate $(git rev-list -g --all)

  1. i checkout last SHA simply
git checkout <SHA>
  1. then i created a brand new branch (named as you prefer) by typing
git switch -c <branch-name> 

Then i got my commits back i pushed the branch all over again

Thank god.

ps: Somehow (SHA) is a commit code

AHMED
  • 121
  • 1
  • 4
8

Make sure to perform all of this locally, and confirm your repo is in the state you desire before pushing to Bitbucket Cloud. It may also be a good idea to clone your current repo, and test these solutions out first.

  1. If you just deleted the branch, you'll see something like this in your terminal:
    Deleted branch <your-branch> (was <sha>)

2.To restore the branch, use:

    git checkout -b <branch> <sha>

If you don't know the 'sha' off the top of your head, you can:

  1. Find the 'sha' for the commit at the tip of your deleted branch using:
    git reflog
  1. To restore the branch, use:
    git checkout -b <branch> <sha>

If your commits are not in your reflog:

  1. You can try recovering a branch by reseting your branch to the sha of the commit found using a command like:
    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

2.You can then display each commit using one of these:

    git log -p <commit>
    git cat-file -p <commit>
Robbie JW
  • 729
  • 1
  • 9
  • 22
uyghurbeg
  • 176
  • 3
  • 8
7

For recovering a deleted branch, First go through the reflog history,

git reflog -n 60

Where n refers to the last n commits. Then find the proper head and create a branch with that head.

git branch testbranch HEAD@{30}
sajin tm
  • 323
  • 3
  • 9
4

I rebased a branch from remote to try to clear a few commits I didn't want and was going to cherrypick the right ones that I wanted. Of course I wrote the SHAs wrong...

Here is how I found them (mostly an easier interface/interaction from things on answers here):

First, generate a list of loose commits in your log. Do this as soon as possible and stop working, as those may be dumped by the garbage collector.

git fsck --full --no-reflogs --unreachable --lost-found > lost

This creates a lost file with all the commits you will have to look at. To simplify our life, let's cut only the SHA from it:

cat lost | cut -d\  -f3 > commits

Now you have a commits file with all the commits you have to look.

Assuming you are using Bash, the final step:

for c in `cat commits`; do  git show $c; read; done

This will show you the diff and commit information for each of them. And wait for you to press Enter. Now write down all the ones you want, and then cherry-pick them in. After you are done, just Ctrl-C it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gcb
  • 13,901
  • 7
  • 67
  • 92
4

A very common sub problem of the general problem of recovering deleted branches is recovering a feature branch after merging and then deleting it - as is common practice.

As this SO post covers you can always recover a deleted branch if it has been merged successfully. This is because a branch is just a fancy pointer to a commit and because you've merged, the commit is still there. A merge commit will list the hash of the head commits of the two (or more) branches merged. For example:

        git show master
        commit 849675951d41497e7b07d34096ebf36dc713221 (HEAD -> master)
        Merge: fc1c9ce 97f8a60
        Author: Me
        Date:   Sun Jan 9 16:14:24 2022 +0100

            Merge branch 'feature'

So you can recover the delete 'feature' branch by doing git checkout -b feature 97f8a60 - no need for any reflog stuff.

user3279360
  • 99
  • 10
2

BIG YES

if you are using GIT follow these simple steps https://confluence.atlassian.com/bbkb/how-to-restore-a-deleted-branch-765757540.html

if you are using smartgit and already push that branch go to origin, find that branch and right click then checkout

Aljohn Yamaro
  • 2,629
  • 25
  • 22
2

I did this on the computer which i delete the branch:

git reflog

response:

74b2383 (develope) HEAD@{1}: checkout: moving from master to develope
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{2}: checkout: moving from develope to master
74b2383 (develope) HEAD@{3}: checkout: moving from master to develope
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{4}: reset: moving to HEAD
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{5}: clone: from http://LOCALGITSERVER/myBigProject/Android.git

and i retrieve the branch with this command:

git checkout -b newBranchName 74b2383

Ammar Bozorgvar
  • 1,230
  • 19
  • 30
2

If you are using Git Extensions

Although old, this thread is the top of the list when you google recovering deleted branches. I use git extensions rather than the command line and so am unfamiliar with the commands but the reflog command gave me a clue so I'm posting my git extensions solution here for others that are using git extensions who may read this.

  1. Go to the view dropdown on the tool bar
  2. Select Show reflog references

Your deleted branch should now be viewable and selectable, simply click on it and check it out.

Dax
  • 63
  • 5
0

First go to git batch the move to your project like :

cd android studio project
cd Myproject
then type :
git reflog

You all have a list of the changes and the reference number take the ref number then checkout
from android studio or from the git betcha. another solution take the ref number and go to android studio click on git branches down then click on checkout tag or revision past the reference number then lol you have the branches.

itsdarrylnorris
  • 630
  • 5
  • 21
0

Adding to tfe's answer, you can recover with this process mentioned, unless it's commits are not garbage collected. Git branch is simply a pointer to a particular commit in the commit tree. But if you delete the pointer, and the commits on that branch are not merged into other existing branch, then git treats it as dangling commits and removes them during garbage collection, which it may run automatically periodically.

If your branch wasn't merged to an existing branch, and if it was garbage collected, then you will loose all commits up until the point from where branch was forked from an existing branch.

meow
  • 307
  • 4
  • 16
0

Just using git reflog did not return the sha for me. Only the commit id (which is 8 chars long and a sha is way longer)

So I used git reflog --no-abbrev

And then do the same as mentioned above: git checkout -b <branch> <sha>

MarvinVK
  • 2,964
  • 1
  • 22
  • 21
0

IF you are using VSCode... and you synced your branch with the server at some point before deleting it...

Note that git branch delete only deletes the local copy, not the copy on the server. First, in the Git panel (git icon on left toolbar), look through the branches and see if your branch is still there under "origin/your_branch_name". If so, just select that and you should get your code back (suggest that you immediately copy/paste/save it locally somewhere else).

If you didn't see an "origin/your_branch_name", Install the GitLens extension. This allows you to visually poke around in the server repositories and locate the copy you synced to the server. If you have multiple repositories, note that it might be necessary to have at least one file opened from the desired repository in order to make the repository appear in GitLens. Then:

  1. Open the GitLens panel

  2. Expand the repository

  3. You should see a list of categories: Branches / Contributors / Remotes / Stashes / etc

You should find YourLostTreasure under "Branches" or possibly under "Remotes -> Origins". Hopefully, you will see a branch with the desired name - if you expand it, you should see the files you changed in that branch. Double-click the file names to open them, and immediately back up that code.

If you don't immediately see your lost branch, poke around and if you find something promising, immediately open it and grab the code. I had to poke around quite a bit until I found TheGoldenBranch, and even then the code was missing the last one or two saves (possibly because I failed to sync to server before attempting-a-Branch-Merge-but-accidentally-clicking-Branch-Delete). My search was unnecessarily lengthened because when I first found the branch I wasn't completely sure the name was correct so kept looking, and it took some time to re-find that first branch. (Thus, Carpe Carpum and then keep looking.)

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
0

If you already push branch to remote server then try to use git checkout <branch> and git will try to clone from you're last origin mirror in your local machine.

hsul4n
  • 491
  • 7
  • 15