WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Git · Expert · question 63 of 100

How do you recover lost commits or branches in Git using the ’git reflog’ and ’git fsck’ commands?

📕 Buy this interview preparation book: 100 Git questions & answers — PDF + EPUB for $5

In Git, it is possible to recover lost commits or branches using the git reflog and git fsck commands. The git reflog command displays a log of all the references that have been updated in the repository, including the commit history, branch history, and HEAD position. This command is useful for tracking down lost commits or branches that may have been accidentally deleted or overwritten.

Here are the steps to recover lost commits or branches using git reflog and git fsck:

First, use the git reflog command to find the commit or branch that was lost. The output of this command will show the history of all changes to the repository, including branch and HEAD movements.

    $ git reflog

Identify the commit or branch that was lost from the output of the git reflog command, and make a note of its SHA hash or branch name.

Use the git fsck command to check the integrity of the repository’s object database. This command will scan the database for any corrupted or missing objects and display a report.

    $ git fsck --lost-found

The git fsck command will generate a list of dangling commits, which are commits that are not connected to any branch or tag. Look for the lost commit or branch in this list.

Once you have identified the lost commit or branch, create a new branch at that commit using the git branch command. For example:

    $ git branch recover-commit 123abc

If you have recovered a branch, switch to that branch using the git checkout command. For example:

    $ git checkout recover-branch

If you have recovered a commit, you can create a new branch from that commit and switch to it using the following commands:

    $ git branch new-branch 123abc
    $ git checkout new-branch

By following these steps, you can recover lost commits or branches in Git using the git reflog and git fsck commands. It is important to note that these commands should be used with caution, as they can modify the repository’s history and should be used only when necessary.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Git interview — then scores it.
📞 Practice Git — free 15 min
📕 Buy this interview preparation book: 100 Git questions & answers — PDF + EPUB for $5

All 100 Git questions · All topics