Git Reflog: Undo Commits and Deleted Branches

saurav omar
3 min readAug 12, 2019

--

Have you ever came accross situation where you have deleted the branch accidently before merging to main branch. here comes git reflog to rescue you from these kind of situations.

One of the things Git does in the background while you’re working away is keep a reflog — a log of where your HEAD and branch references have been for the last few months.

Every time your branch tip is updated for any reason, Git stores that information for you in this temporary history. And you can specify older commits with this data, as well.

The reflog command keeps a track of every single change made in the branches or tags of a repository and keeps a log history of the branches and tags that were either created locally or checked out.

Some important points:

  • reflog history is not shared — it is exclusive to your repository.
  • The branch will be recoverable from your working directory only if the branch ever existed in your local repository because it is related to changes which is affected by local repository. So in case any branch which lost by developed should be checked in developer laptop.

Difference Between Git log and Git reflog:

  • git log shows the commit log accessible from the refs (heads, tags, remotes)
  • git reflog is a record of all commits that are or were referenced in your repo at any time.

Not clear !! Don’t worry you will understand in up coming lines.

How can we recover from delete branches?

  • Let’s say i am in branch master.
  • Now i have checkout new branch feature and made some changes and commited, now my git reflog look like this.
git reflog9af2170 (HEAD -> feature) HEAD@{0}: checkout: moving from master to featurea8617b3 (origin/master, origin/HEAD, master) HEAD@{1}: checkout: moving from feature to master9af2170 (HEAD -> feature) HEAD@{2}: commit: update read me
  • Let’s say i have delete the branch without pushed to remote by mistake.
  • Oops!! it shows error because this is not yet merged. we use git branch -D feature
  • Now here comes the recovery part. Ot git reflog looks something like this.
  • As we can see from the above we have checkout Head@{3} or commit 9af2170 here we have made come changes.
  • Yay !! we have recoverd what we have lost.

We have seen how can we recover from lost commits or branches. Most of the time we came accross these kind of situations here is git reflog to the rescue.

That’s it.

Happy Learning.

If you like this article please do claps and share accross within you cirlce.

--

--

saurav omar
saurav omar

Written by saurav omar

Geek and Always ready to give more than 100%

No responses yet