0
0
Gitdevops~30 mins

Recovering lost commits with reflog in Git - Mini Project: Build & Apply

Choose your learning style9 modes available
Recovering Lost Commits with Reflog
📖 Scenario: You accidentally deleted some commits in your Git repository. You want to recover those lost commits using Git's reflog feature.
🎯 Goal: Learn how to use git reflog to find lost commits and restore your branch to a previous state.
📋 What You'll Learn
Use git reflog to view recent HEAD changes
Identify the commit hash of the lost commit
Use git reset --hard <commit-hash> to restore the branch
Verify the branch points to the recovered commit
💡 Why This Matters
🌍 Real World
Developers often accidentally lose commits by resetting branches or deleting branches. Using reflog helps recover those commits quickly without losing work.
💼 Career
Knowing how to recover lost commits is a valuable skill for software developers and DevOps engineers to maintain code integrity and avoid data loss.
Progress0 / 4 steps
1
Initialize a Git repository and create commits
Run git init to create a new Git repository. Then create a file named file.txt with the content First line. Add and commit this file with the message Initial commit. Next, append Second line to file.txt, add and commit with the message Second commit.
Git
Need a hint?

Use git init to start a repo. Use echo to write to files. Use git add and git commit to save changes.

2
Simulate losing commits by resetting branch
Use git log --oneline to find the commit hash of the Initial commit. Then run git reset --hard <initial-commit-hash> to move the branch back to the first commit, losing the second commit from the branch history.
Git
Need a hint?

Use git log --oneline to get short commit hashes. Use shell commands to extract the hash. Then reset hard to that hash.

3
Use reflog to find lost commit hash
Run git reflog to see recent HEAD changes. Identify the commit hash of the lost Second commit from the reflog output. Assign this hash to a variable named lost_commit using shell commands.
Git
Need a hint?

Use git reflog and grep to find the commit message. Extract the commit hash with cut or awk.

4
Restore the lost commit using reset
Use git reset --hard $lost_commit to restore the branch to the lost commit. Then run git log --oneline -1 to print the latest commit message and verify it is Second commit.
Git
Need a hint?

Use git reset --hard $lost_commit to restore. Use git log --oneline -1 --pretty=%s to print the commit message only.