Git Reflog – How to recover a deleted branch that was not merged

Last updated on Sep 14,2024 7.3K Views
A passionate Content Developer with key skills – Git, Dockers, Databases, Linux... A passionate Content Developer with key skills – Git, Dockers, Databases, Linux and Unix.

Git Reflog – How to recover a deleted branch that was not merged

edureka.co

“Have you ever lost a branch, whose source code was not yet merged in the ‘release’ branch or the ‘main’ branch? What if you want to regenerate a deleted branch though its work has already been merged into the main branch?”. Well, the only solution to such scenarios is Git Reflog.

Through this article on Git Reflog, I will help you understand the scenarios in which your work on a branch could be lost and how to recover the branch. Also, this article will highlight the approach you could take to prevent the unintended loss of a branch while working in a large project.

    1. What is Git Reflog?
    2. How and when a branch gets deleted?
    3. Recover a deleted branch
    4. What work is restored when the deleted branch is recovered?
    5. Git Reflog Sub-commands

So, let us get started with this article.

Consider a scenario, a maintainer has to merge many feature branches from different collaborators and then delete them eventually; but the branch is deleted accidentally before the work could be merged?

Well, before I move on this article, let me tell you that it is not possible in Git. Git commands are secure and act as a check post; would not allow you to do so. So, this where Git Reflog comes into the picture.

What is Git Reflog?

The ‘reflog’ command keeps a track of every single change made in the references (branches or tags) of a repository and keeps a log history of the branches and tags that were either created locally or checked out. Reference logs such as the commit snapshot of when the branch was created or cloned, checked-out, renamed, or any commits made on the branch are maintained by Git and listed by the ‘reflog’ command.

Note:  The branch will be recoverable from your working directory only if the branch ever existed in your local repository i.e. the branch was either created locally or checked-out from a remote repository in your local repository for Git to store its reference history logs.

This command has to be executed in the repository that had the lost branch. If you consider the remote repository situation, then you have to execute the reflog command on the developer’s machine who had the branch.

command: git reflog

Now that you know, what is Git Reflog, let us try to delete both a merged and an un-merged branch and see how Git handles that?

Step 1: List the branches that are merged into master

First, check out into the ‘master’ branch if you are on some other branch using the command:

$git checkout master

Output

Now, to get a list of merged branches, mention the following command:

$git branch --merged

Output:

Step 1.1: Then, delete the merged branch:

$git branch -d issue#902

Output:

The branch ‘issue#902’ was successfully deleted as it is already merged into the ‘master’ branch.

Step 2: Now, let us list the branches which are not-merged into master.

$git branch --no-merged

Output

Step 2.2: Finally, let us delete an un-merged branch with the following command:

$git branch -d prepod

If you try to delete one of the branches with un-finished work say “preprod” branch, git displays a warning message.

Output

Now, before I tell you how you can recover the data this article on Git Reflog, let me tell you what exactly happens when a branch gets deleted and under what circumstances can the branch be recovered.

How and when a branch gets deleted?

As we know that Git is a Distributed Version Control System (DVCS), every machine with the clone or a copy of the repository act as both node and a hub. This implies that each machine will have its own copy of the entire repository code and history. Needless to say; you will be sharing your work with others and publishing the same.

Hence, in such scenarios, there could be 3 cases when a branch gets deleted in a real-world scenario with many contributors working on a large project. The following could be the cases:

Case 1 – A Developer can either merge or delete the branch

Consider a scenario where a developer merges the feature branch into the main branch locally and then deletes the feature branch using the ‘git branch’ command with the “-d” flag as seen in the earlier screenshots.

Command: ‘git branch -d branch_name’

It could also happen that the developer decides to trash the changes on the branch and decides to delete the branch without merging it with any other branch using the following command:

Command: ‘git branch -D branch_name’

With the above command, the developer is forcefully delete the  branch overriding the git warning 

$git branch -D preprod

Output

Note: ‘preprod’ branch will no longer be listed when you run the ‘git branch’ command. So, your work saved on this branch will be lost.

Case 2 – A Developer deletes a branch in a shared repository 

Consider a scenario, where a developer with read/write access tries delete the remote branch forcefully by using the ‘git push’ command with the ‘–delete’ flag.

$git push origin --delete quickfix

Output

Apart from this, there could also be a case where an un-authorized or malicious user forces a push to delete the remote branch. In such case, the maintainer will be able to recover the deleted ‘quickfix’ branch only if the developer had previously checked out this branch. In this scenario, its local repository will still have reference logs of it.

If the maintainer cannot recover the branch, then the owner of the branch who deleted it must recover from his/her local reflogs.

Case 3 – A hook script with super privileges deletes the branch

This could be a rare but, a possible scenario that a hook script gets triggered at certain git operation event and force deletes the branches that are not merged yet. You can consider one of the above mentioned commands being scripted in a hook script with sudo privileges.

Now, that you know what happens, when you delete the branch, let us move on with this article on Git Reflog and see how to recover a lost branch.

Recover a deleted branch using Git Reflog

Step 1: History logs of all the references

Get a list of all the local recorded history logs for all the references (‘master’, ‘uat’ and ‘prepod’) in this repository.

git reflog

Step 2: Identify the history stamp 

As you can refer from the above snapshot, the Highlighted commit id: e2225bb along with the HEAD pointer index:4 is the one when ‘preprod’ branch was created from the current HEAD pointer pointing to your latest work.

Step 3: Recover

To recover back the ‘preprod‘ branch use the command  ‘git checkout’ passing the HEAD pointer reference with the index id – 4. This is the pointer reference when ‘preprod’ branch was created long commit id highlighted in the output screenshot.

git checkout -b preprod HEAD@{4}

Output

And voila! ‘preprod‘ branch is recovered back with all of your source code.

NOTE: Let me breakup the ‘git checkout’ command used above and help you understand better:

‘git checkout’ command is an over-loaded command (Just like any Java overloaded function). This is the part where the actual branch is recovered.

This single command first checks out to the earlier history timestamp pointed by the HEAD@{4} pointer and then creates a branch with the name ‘preprod’ using the “-b” option; as well as switches your working directory to the newly created branch.

This implies that the branch switched will be from ‘master’ to ‘preprod’ as indicated in the output screen. You could now merge it with ‘master’ or the ‘release’ branch as per your branching model.

Now, that you know how to restore a branch, let me tell you what work is restored when a deleted branch is recovered.

What work is restored when the deleted branch is recovered?

The files which were stashed and saved in the stash index list will be recovered back. Any untracked files will be lost. Also, it is a good idea to always stage and commit your work or stash them.

To fetch the log references of a particular branch or tag run the command – “git reflog <ref_name>”. 

Example: To check the log references of ‘uat’ branch alone use the command – “git reflog uat”.

Git Reflog Sub-commands

git reflog

Command to open up the manual page

$git reflog --help

Output

git reflog show 

Shows the logs of the reference provided in the command line.

git reflog show master@{0}

git reflog expire 

This command is used to prune the older reflog entries.

git reflog expire

git reflog delete 

This command deletes single entries from the reflog history.

git reflog delete

git reflog exists 

This command checks whether a ref (branch or tag) has a reflog – log history entries.

git reflog exists

Apart from the above-mentioned commands, The “Git Reflog” command takes various subcommands, and different options depending on the subcommands mentioned above. For further reading run “git reflog –help” from the terminal window.

With this, we come to an end to this article on Git Reflog. The intention of DevOps is to create better-quality software more quickly and with more reliability while inviting greater communication and collaboration between teams. If you are intrigued by this article, check out the DevOps Online Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. The Edureka DevOps Certification Training course helps learners to understand what is DevOps and gain expertise in various DevOps processes and tools such as Puppet, Jenkins, Nagios, Ansible, Chef, Saltstack and GIT for automating multiple steps in SDLC.

Got a question for us? Please mention it in the comments section of ”Git Reflog” article and we will get back to you ASAP. 

Upcoming Batches For DevOps Certification Training Course
Course NameDateDetails
DevOps Certification Training Course

Class Starts on 23rd November,2024

23rd November

SAT&SUN (Weekend Batch)
View Details
DevOps Certification Training Course

Class Starts on 25th November,2024

25th November

MON-FRI (Weekday Batch)
View Details
DevOps Certification Training Course

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Decoding the DevOps Periodic Table