10 Tricky Git Interview Questions and Answers

·13 min read
By ·Updated
gitinterview-questionsversion-controldevopsdeveloper-tools

These 10 Git questions test the state model behind everyday recovery commands: refs, HEAD, the index, the working tree, reflogs, object reachability, and the commit graph. State-changing commands are shown with explicit cautions because memorizing a “magic undo” is how recoverable mistakes become data loss.

Table of Contents

  1. Reset vs Revert Questions
  2. Reflog Recovery Questions
  3. Detached HEAD Questions
  4. Cherry-Pick Questions
  5. Git Bisect Questions
  6. Quick Reference

Reset vs Revert Questions

These questions test your understanding of Git's two primary ways to undo changes.

What is the difference between git reset and git revert?

In commit form, git reset moves HEAD or the current branch to any selected commit and changes the index/working tree according to the mode. Path and patch forms instead change staged content. Reset does not immediately delete commit objects; it changes reachability from a ref.

git revert applies an inverse change and normally creates a new commit. It leaves the original commit reachable, but the inverse can conflict and may not restore all external effects. Reverting a merge requires a mainline parent and affects how later merges treat that topology.

# You've made three commits on main that need to be undone
# The commits have already been pushed to origin
git log --oneline
# a1b2c3d Fix payment bug
# e4f5a6b Add logging
# 17d8c9e Update config
# b0c1d2e Previous good state

Wrong for this protected/shared-ref policy: git reset --hard b0c1d2e followed by git push --force

Policy-compatible approach: review and revert the commits in the intended order, for example git revert a1b2c3d e4f5a6b 17d8c9e.

When you reset on a shared branch and force-push, you're rewriting history that exists on other developers' machines. When they pull, Git gets confused because their local history no longer matches remote. This leads to duplicate commits, lost work, and angry teammates.

Revert advances the shared ref instead of replacing its previous tip, which fits an append-only policy. It is not risk-free: inspect the combined inverse, run tests, and communicate operational side effects that Git cannot undo.

# Safe way to undo the last 3 commits
git revert HEAD~3..HEAD
 
# Or revert a specific commit
git revert a1b2c3d --no-edit
 
# Revert a merge commit (specify which parent to keep)
git revert -m 1 <merge-commit-hash>

When should you use each type of git reset?

For commit-form reset, --soft moves HEAD but leaves the index and working tree unchanged; --mixed also resets the index and is the default; --hard resets the index and tracked working-tree files, discarding conflicting tracked changes. Untracked files in the way can also be deleted. Inspect status and create a rescue ref before a destructive reset.

# Soft reset: uncommit but keep changes staged
git reset --soft HEAD~1
 
# Mixed reset: uncommit and unstage, but keep changes in working directory
git reset HEAD~1
 
# Hard reset: preserve the old tip first; tracked changes can be lost
git branch rescue/before-hard-reset
git reset --hard HEAD~1

Reflog Recovery Questions

These questions test how you gather recovery evidence before changing more state.

How do you recover deleted branches or lost commits?

Reflogs record local updates to refs; the HEAD reflog also records branch switches. A deleted branch's own reflog can be removed with the ref, so inspect git reflog --all and any surviving HEAD or other-ref entries. Once you identify a candidate, inspect it and create a rescue ref before reset or cherry-pick.

Unreachable objects are often retained temporarily, but reflog expiry and garbage collection mean recovery is not guaranteed:

# You accidentally deleted a branch with important work
git branch -D feature-important
 
# Or you ran a hard reset and lost commits
git reset --hard HEAD~5
 
# See the reflog to find your lost work
git reflog
 
# Output shows something like:
# a1b2c3d HEAD@{0}: reset: moving to HEAD~5
# f9e8d7c HEAD@{1}: commit: Add user authentication
# b5a6c7d HEAD@{2}: commit: Fix login bug
# b0c1d2e HEAD@{3}: checkout: moving from main to feature-important

Each entry has a reference like HEAD@{n} that you can use to travel back in time:

# Resolve and inspect the candidate, then preserve it
git rev-parse HEAD@{1}
git show --stat f9e8d7c
git branch recovered-branch f9e8d7c
 
# Or cherry-pick specific lost commits
git cherry-pick f9e8d7c b5a6c7d

Reflogs are local. Default expiry is commonly 90 days for reachable entries and 30 days for entries unreachable from the current tip, but configuration and maintenance can change this. If the object is gone locally, inspect remote refs, tags, backups, CI artifacts, or another clone.

What is ORIG_HEAD and how does it help with recovery?

Some operations record the previous tip in ORIG_HEAD, making it a useful candidate after a merge, reset, or rebase. It is a single mutable ref, not a durable history: later commands can overwrite it, and the rebase implementation may move it while operating. Inspect it before use and preserve it with a branch.

# Inspect and preserve the candidate before changing HEAD
git show --stat ORIG_HEAD
git branch rescue/orig-head ORIG_HEAD

Detached HEAD Questions

These questions test the relationship between HEAD, branches, and object reachability.

What is detached HEAD state and why does it matter?

Detached HEAD means HEAD identifies a commit directly rather than symbolically naming a local branch. Commits work normally, but after you move elsewhere the new commits may have no branch/tag pointing to them and remain reachable only through reflogs until expiry and pruning.

Understanding this requires knowing what HEAD is. HEAD is normally a symbolic reference—it points to a branch name like refs/heads/main, and that branch points to a commit. When HEAD is "detached," it points directly to a commit hash instead of a branch.

Think of branches as named bookmarks in a book. HEAD is the page you're currently reading. Normally HEAD says "I'm reading the page that the 'main' bookmark points to." In detached HEAD state, HEAD says "I'm reading page 47" with no bookmark involved.

git checkout a1b2c3d
# You are in 'detached HEAD' state...
 
# You make some commits
git commit -m "Experimental feature"
git commit -m "More experiments"
 
# Then you checkout main
git checkout main
 
# Those commits are no longer named by a branch; recover them via reflog if needed.

How do you save work done in detached HEAD state?

Create a branch before switching away. This gives the wanted commit a durable local ref:

# The fix: create a branch before switching away
git checkout a1b2c3d
git commit -m "Experimental feature"
git switch -c save-my-experiments
git switch main

Detached HEAD is useful for inspecting, building, or testing an exact commit. If you already switched away, find the commit in git reflog and create a branch before it expires.


Cherry-Pick Questions

These questions test practical Git workflow knowledge.

When should you use git cherry-pick?

Cherry-pick applies the change introduced by selected commits onto the current branch and normally creates new commits without recording the source commits as parents. The resulting patch need not be identical after context changes or conflict resolution.

# You're on the release-2.0 branch
# A critical bugfix was committed to main
# You need ONLY that bugfix, not other main commits
 
git log main --oneline
# f1e2d3c Refactor user service (DON'T WANT)
# a4b5c6d Fix critical payment bug (WANT THIS)
# 97a8b9c Add new feature (DON'T WANT)
 
git checkout release-2.0
git cherry-pick a4b5c6d

When to use cherry-pick:

  • Applying hotfixes to multiple release branches
  • Recovering specific commits from an abandoned branch
  • Pulling in a single feature without merging an entire branch

When to reconsider cherry-pick:

  • When repeated copying obscures which branches contain equivalent changes
  • When you need many commits (consider merging instead)
  • When commits have dependencies on each other

When should you use the -x flag with cherry-pick?

The -x flag appends a provenance line naming the source commit when a conflict-free cherry-pick is recorded. Git documents it as useful when copying between publicly visible branches, such as a maintenance backport, but unnecessary for a private source branch. Follow project policy and do not treat the trailer as proof that patches remain identical.

git cherry-pick -x a4b5c6d
# Commit message automatically includes:
# (cherry picked from commit a4b5c6d)
 
# Cherry-pick a linear range; inspect the revision set first
git log --oneline --reverse A^..B
git cherry-pick A^..B
 
# Cherry-pick without committing (stage changes only)
git cherry-pick -n a4b5c6d
 
# Handle conflicts during cherry-pick
git cherry-pick a4b5c6d
# ... resolve conflicts ...
git status
git add path/to/resolved-file
git cherry-pick --continue

Git Bisect Questions

These questions test whether you can define a trustworthy regression predicate and interpret the result.

What is git bisect and how does it find bugs?

git bisect searches the commit graph between known good and bad boundaries by checking out candidate revisions for classification. With a reproducible, monotonic condition and testable history, the number of classifications is roughly logarithmic. Merge topology, skipped commits, flaky tests, build breaks, and external dependencies can complicate or make the result ambiguous.

# Users report that login is broken
# It worked in version 2.0 (commit abc123)
# It's broken in current main (commit 9f8789a)
# There are 200 commits between them
 
# Start bisect
git bisect start
 
# Mark current commit as bad
git bisect bad
 
# Mark known good commit
git bisect good abc123
 
# Git checks out a commit in the middle
# Bisecting: 100 revisions left to test
 
# Test the login functionality, then:
git bisect good  # if login works
# or
git bisect bad   # if login is broken
 
# Git narrows down further
# Bisecting: 50 revisions left to test
 
# Repeat until:
# a4b5c6d is the first bad commit

How do you automate git bisect with a test script?

git bisect run expects exit 0 for good, 1–127 except 125 for bad, and 125 for an untestable commit that should be skipped; other exits abort. Do not pass a generic test command unless every nonzero status really means the target regression. A wrapper should distinguish build/environment failure from the behavior being classified and clean up files, services, databases, and remote side effects.

# The wrapper maps target behavior to good/bad and untestable builds to 125
git bisect start HEAD abc123
git bisect run ./scripts/bisect-login.sh
 
# Git checks out and classifies candidates automatically.

When you're done:

git bisect reset  # Returns to original HEAD

After git bisect reset, verify the reported candidate manually in a clean, representative environment. A large commit can still be the first bad boundary while requiring finer diagnosis; skipped adjacent commits can leave a set of possible first-bad commits rather than one answer.


Quick Reference

CommandPurposeSafety
git reset --softMove HEAD, keep index/worktreeRewrites ref; preserve old tip
git reset --mixedMove HEAD and reset indexWorking tree retained where possible
git reset --hardMatch HEAD/index/tracked worktreeDestructive; inspect and rescue first
git revertRecord inverse changeAppend-only ref update; can conflict
git reflog --allInspect local ref updatesLocal and expiring evidence
git cherry-pickApply specific commitCreates new hash
git cherry-pick -xAdd source trailerUseful for public-branch backports
git bisectSearch graph by classificationsChecks out commits; test may mutate state
ORIG_HEADCandidate previous tipMutable; inspect and preserve

Key mental model: Git stores content-addressed objects and moves refs that name them. Most repositories use SHA-1 object IDs, while Git also supports a SHA-256 repository format. HEAD can symbolically name a branch or identify a commit directly. The index and working tree are separate states. Reflogs and ORIG_HEAD can aid recovery, but both are local or mutable and objects can eventually be pruned—create a rescue ref before experimenting.



Tricky Git FAQ

What is the difference between git reset and git revert?

In commit form, git reset moves HEAD or the current branch to a chosen commit and updates the index and working tree according to its mode; path and patch forms adjust staged content instead. git revert applies an inverse change and normally records a new commit. Prefer revert where a shared ref must keep an append-only trail; use reset only when moving the ref is authorized and you understand what its mode discards.

How do you recover a deleted branch or lost commits in Git?

Stop making changes, inspect git status and git reflog --all, resolve the candidate to an object ID, inspect it, and create a rescue branch before doing anything destructive. Reflogs are local: reachable entries default to 90-day expiry and unreachable entries to 30 days, both configurable, and a deleted branch's own reflog can disappear. If no local reflog retains it, check remote refs, tags, backups, CI artifacts, or another clone.

What is git bisect and when would you use it?

git bisect searches a commit graph between known good and bad boundaries by checking out candidate revisions for classification. Use it for a reproducible, approximately monotonic regression with trustworthy boundaries. It can identify a first bad commit, but skipped or untestable commits can leave multiple candidates, and the test environment or external state can invalidate the conclusion.

When should you use git cherry-pick?

Use cherry-pick to apply the changes introduced by selected commits, such as a reviewed backport or a commit made on the wrong branch. It normally creates new commits without preserving the source commits as parents, so account for dependencies, conflicts, duplicate patches, and future merges. The -x provenance trailer is useful between public branches, but Git explicitly says it is unnecessary for a private source branch.

What happens in a detached HEAD state in Git?

Detached HEAD means HEAD identifies a commit directly instead of symbolically naming a local branch. You can inspect, build, and commit normally, but moving elsewhere can leave new commits reachable only through reflogs or other references. Before leaving, preserve wanted work with git switch -c new-branch or git branch new-branch COMMIT; if you already left, find it in the local reflog and create a rescue ref.

How do you undo a git rebase that went wrong?

While a rebase is active, use git rebase --abort to return to its recorded pre-rebase state. After completion, inspect the reflog, resolve the old tip to a SHA, and create a rescue branch. Only then choose how to restore or compare it. ORIG_HEAD may help but can be overwritten by later commands; reflogs are local and expire. Avoid reflexive git reset --hard because it discards tracked index and working-tree changes.

Sources

Ready to ace your interview?

Get 550+ interview questions with detailed answers in our comprehensive PDF guides.

View PDF Guides