Git Interview Questions and Answers for 2026

Git interview questions open almost every DevOps, SRE, platform, and software engineering loop, because every team lives in version control and every incident ends in a commit. This page is a complete, tiered bank: 104 questions with worked answers, split into beginner, intermediate, and scenario sections, plus hands-on labs, a command cheat sheet, and a five-question quiz at the end. Work through it in order, or jump straight to the tier that matches your next round.

Git interview questions tiered bank covering branching, rebasing, reflog recovery, and history surgery
The three tiers in this bank: daily-driver fluency, storage mechanics, and recovery under pressure.

TL;DR

  • 104 questions, three tiers. Beginner daily-driver fluency, intermediate object and ref mechanics, and realistic recovery scenarios, each answered the way interviewers want to hear it.
  • Answers name the mechanism. Blobs, trees, refs, reflogs, merge bases: every answer gives the command and then explains what Git is actually doing, because that second half is what Git interview questions grade.
  • Practice is built in. Three safe-to-break labs, a cheat sheet of the commands behind the answers, and a five-question quiz to check what stuck.

How the Git interview works in 2026

Most Git interview questions arrive in one of three rounds. The first is the screening call, often with the hiring manager or a senior engineer, and it runs on confidence filters: what the staging area is for, fetch versus pull, the difference between merge and rebase, why a force push is dangerous. These are thirty-second answers with one level of depth behind them. Nobody expects a lecture at this stage; they expect precision, because fumbling fetch versus pull usually means copying commands rather than running them.

The second round is the deep technical, and this is where Git interview questions turn mechanical: the four object types, what a branch physically is on disk, what the reflog records, what each reset mode moves, what a merge base is and how a three-way merge uses it. Interviewers at this stage listen for mechanism language. Saying reset –hard moves the branch, the index, and the working tree to the target commit passes a working-engineer bar; saying reset undoes commits does not. The graders are sorting people who memorized command lists from people who know what the commands touch, and Git interview questions at this level are decided on that distinction.

The third round is the scenario round, sometimes live on a terminal, sometimes whiteboard, and increasingly a take-home against a prepared broken repo. You get the damage in one sentence: I committed to the wrong branch, a teammate force-pushed over my work, there is an API key in the history and the repo is public. What gets scored is your diagnostic order: check what is shared before choosing a tool, reach for the reflog before reaching for panic, pick revert over rewrite whenever strangers have the commits. Most scenario Git interview questions are lost by candidates who name a command first and ask questions never.

Role shape moves the emphasis. DevOps and platform loops weight the collaboration surface: hooks and policy enforcement, protected branches, CI clone mechanics, monorepo tooling, release tagging. Application team loops weight rebase fluency and conflict resolution, because that is where their day lives. SRE loops add the incident angle: bisecting a regression across a hundred commits, recovering history during an outage, automating checks that keep the graph sane. The base bank on this page is the same for all three; only the follow-up depth moves.

Preparation is unusually cheap for this topic, because Git is the one interview subject you can rehearse destructively on your own machine. Open a scratch repository, break it on purpose, recover it, and say the steps out loud. Reset hard and lose a branch, then get it back from the reflog; rebase a real feature branch and watch the hashes change; force-push with a lease to a toy remote and make it reject you. Candidates who have personally broken and repaired every failure in the scenario tier answer differently, and interviewers can hear the difference. Treat Git interview questions like a performance, and rehearse like it is one.

Core concepts interviewers expect you to know

Three mental models unlock most of the deep half of Git interview questions: the object graph, refs and HEAD with the reflog that watches them, and the rules for when rewriting history is safe. Almost every command in the bank is just one of these three models wearing a different flag. Interviewers open here because the models scale: a candidate who can narrate them can derive answers to questions they have never seen.

The object graph: blobs, trees, commits, tags

Git is a content-addressed object database, and everything else is bookkeeping around it. Four object types exist. A blob holds file bytes and nothing else: no name, no timestamp, just contents. A tree is a directory listing: entries of mode, name, and the blob or subtree each name points at. A commit points at one tree, lists its parent commits, and carries author, committer, timestamps, and a message. A tag object wraps another object with a tagger, date, message, and optionally a signature, which is what an annotated tag actually is. Every object is addressed by the hash of its own content, so identical file contents deduplicate into one blob, and changing a single byte anywhere produces a different hash for that object and every object above it.

Two consequences do most of the work in interviews. First, commits are snapshots, not diffs: each commit names a complete tree, and diffs are computed afterward by comparing snapshots, which is why branching is free and why empty directories do not exist, since trees only list files. Second, hashes are immutable addresses: amend, rebase, and filter-repo do not edit history, they write new objects and move refs to point at them, leaving the old objects in place until garbage collection. That single fact explains the reflog, the danger of force pushes, and why two branches holding the same change can hold different hashes. Show it live with git cat-file -p HEAD^{tree} and git ls-tree HEAD; being able to is what separates narrated answers from real ones in Git interview questions.

commit tree, parents, author, message hash of content tree names + modes pointing at blobs, subtrees blob app.py bytes blob README bytes parent commit its own tree tag object wraps a commit points at lists lists parent annotated tag Every object is named by the hash of its own content.
The object graph: commits point at trees, trees list blobs, commits link to parents, and annotated tags wrap commits.

Refs, HEAD, and the reflog

A branch in Git is a 41-byte text file under .git/refs/heads containing one commit hash. That is the entire mechanism, and it is the answer that reframes every workflow question: branch creation is one file write, which is why Git workflows branch constantly, and moving a branch is rewriting that one line, which is what commit, merge, rebase, and reset all fundamentally do. HEAD is a symbolic ref, usually a file containing ref: refs/heads/main, naming the branch you are on; when it holds a raw hash instead, you are detached. Remote-tracking refs under refs/remotes remember where origin’s branches stood at your last fetch. Once a repository accumulates thousands of refs, Git consolidates them into a single packed-refs file that it reads just as transparently.

The reflog is the local journal of every move HEAD and each ref has made: commits, resets, rebases, checkouts, amends, each one appended with the old and new position. It is what makes almost every lost-work story recoverable: a reset that made commits unreachable did not delete them, it only unwrote their addresses, and the reflog holds the old address for about 90 days by default. The boundary that matters operationally: reflogs live in your clone and are never pushed, so they rescue work that existed on your machine, not history that lived only on someone else’s. Interviewers probe exactly that boundary, because drawing it correctly shows you understand where Git stores truth and where it merely remembers.

Before merge main feature HEAD After fast-forward merge main moved Fast-forward is pure pointer movement: no new commit, perfectly linear history.
Merging two commits of pointer choreography: fast-forward simply slides main up to the feature tip.

Rewriting history and the golden rule

Four tools rewrite history: commit --amend, reset, rebase, and filter-repo for whole-history surgery. None of them edit anything; all of them write new objects with new hashes and move refs onto the new chain, leaving the originals reachable through the reflog until gc expires them. The difference between them is scope: amend touches one commit, reset moves a branch to any point, rebase replays a range onto a new base, and filter-repo rewrites every commit matching a rule, which is the tool for scrubbing secrets or stripping huge files from deep history.

The golden rule that answers a third of all Git interview questions about recovery and workflow: rewrite only commits that exist only on your machine, or on a branch every affected teammate has agreed to abandon. Once strangers have cloned a commit, removing it requires coordinating every clone, which is why shared-branch fixes are reverts and why force pushes, when unavoidable, use --force-with-lease so a teammate’s fresh push cannot be silently destroyed. Secrets are the special case that breaks the rule’s comfort: a scrubbed history does not un-leak a key, so rotation always comes before rewriting.

With those three models in place, the rest of the bank is extension, not memorization: workflows are pointer choreography, hooks are scripts bolted around object writes, conflicts are tree merges the base could not settle, and bisect is binary search over the commit chain. When a question surprises you, derive the answer from the models instead of hunting for a memorized command, because that derivation is the skill the deep half of Git interview questions exists to measure.

Question bank at a glance

The bank below is organized the way Git interview questions are actually asked: broadly increasing difficulty, then the scenario round that finishes most loops. Counts are exact so you can pace the work: a question every few minutes on a commute gets you through the full bank inside a week, with the labs on the weekend and the cheat sheet printed next to your keyboard.

SectionQuestionsWhat it proves
Beginner38You use Git daily and the vocabulary is automatic.
Intermediate40You know the mechanisms: objects, refs, reflogs, merges, rebases.
Scenario and troubleshooting26You can recover a broken repository in a defensible order.

Difficulty rises inside each tier too, so if the last questions of a section feel easy, move up. Every answer pairs the command with the reason it works, because Git interview questions are graded on both halves: the tool, and the sentence explaining what Git does when it runs.

Beginner Git interview questions

These 38 open the bank, and they look easier than they are. Interviewers use the opening tier of Git interview questions to check precision: a crisp one-or-two-sentence answer with exactly one supporting detail, then stop. Say more and you burn round time; say less and you sound like a list. Practice the discipline here, because the same shape repeats at every level above.

What is Git, and what problem does it solve?

Answer: Git is a distributed version control system: it records snapshots of your project with full history locally, and lets many people converge work without a central server being the source of truth. The problem it solves is safe parallel work: branches for experiments, merges to combine them, and a history you can inspect, bisect, and recover from. That snapshot-plus-history model is the foundation most Git interview questions build on, so open with it deliberately.

How is Git different from centralized systems like Subversion?

Answer: Subversion keeps history on one server; you check out a working copy and need the network to see history, branch, or commit. Git gives every clone the complete repository: full history, branching, and merging all work offline, and the remote is a synchronization peer, not the authority. That is why log, blame, and branch are instant locally, and why every clone doubles as a backup, a point worth making in Git interview questions about resilience.

What are the three states a file can be in?

Answer: Modified, staged, and committed. Modified means changed in the working tree since the last commit; staged means recorded in the index and bound for the next commit; committed means stored in the local object database. The flow is edit, add, commit. A fourth label, untracked, covers files Git has never recorded. Three-state fluency is what the opening tier of Git interview questions checks first.

What does git init do, and how is it different from git clone?

Answer: git init creates a fresh repository in the current directory: the .git object database, refs, and config, with nothing recorded yet. git clone copies an existing repository, history included, configures a remote named origin, and checks out a working tree. One level deeper: init --bare creates a repository without a working tree, which is what servers point pushes at, and naming it shows you have set up a remote before.

What is the staging area, and why does Git have one?

Answer: The index holds exactly what the next commit will contain. You shape a commit deliberately: stage two of five changed files, review with git diff --staged, then commit only what belongs together. That is why Git commits can be clean, atomic units instead of whatever happened to be dirty at the time. Atomic commits are what code review and bisect both depend on, which is why this question anchors so many Git interview questions.

What is the difference between git add . and git add -A?

Answer: Both stage changes, with a scope difference: git add . stages everything under the current directory, while git add -A stages the whole repository, deletions included. Since Git 2.x the two behave identically when run from the repo root, which is the trap: run add . from a subdirectory and you silently stage less than you think. Staging-scope bugs show up in Git interview questions more often than people expect, because everyone has shipped one.

What does a commit record?

Answer: A commit points to a tree, the full snapshot of every tracked file at that moment, lists its parent commits, and carries author, committer, timestamp, and message. It does not store diffs; diffs are computed by comparing snapshots. This design explains instant branching, free deduplication of unchanged files, and why changing any part of history produces brand new hashes, a consequence the whole intermediate tier of Git interview questions builds on.

What is HEAD?

Answer: HEAD says where you are: normally the name of the current branch, which itself points at the latest commit. Every commit you make advances the branch HEAD names. HEAD~1 is its parent, HEAD~2 the grandparent, and relative ranges like HEAD~3..HEAD scope most commands. When HEAD holds a raw commit hash instead of a branch name, you are in detached HEAD state, which has its own entry later in this bank.

What is a branch, really?

Answer: A branch is a movable pointer to one commit: a tiny text file under .git/refs/heads containing a hash. Creating one is instant and free, which is why Git workflows branch constantly, one topic per branch. Deleting a branch deletes the pointer, not the commits; the commits become unreachable only when no branch, tag, or other reference points at them. Saying the file-and-pointer sentence is what beginner Git interview questions on branching are listening for.

What does git status tell you, and why run it before committing?

Answer: It reports the current branch, files modified but not staged, files staged for the next commit, untracked files, and any in-progress operation like a merge or rebase. Running it before every commit is the cheapest quality habit in Git: it catches the forgotten file, the accidental staging, and the wrong branch, all harder to fix after a push. Status is also step one of nearly every recovery flow in the scenario tier.

How do you read history with git log?

Answer: git log lists commits newest first with full metadata; --oneline compresses each to one line; --graph draws the branch topology; -p attaches each commit’s diff; -S string finds where text entered or left the codebase; -- path scopes history to one file. Reading topology with --graph --oneline --all is the skill behind most follow-up Git interview questions about merges and rebases, so make it muscle memory.

What is the difference between git diff, git diff –staged, and git diff HEAD?

Answer: git diff shows working-tree changes not yet staged. git diff --staged shows staged changes versus the last commit, which is exactly what the next commit will contain. git diff HEAD shows the combined difference, staged plus unstaged. Pick the variant that answers the question you are actually asking: about to commit, use --staged; confused about what changed at all, use HEAD. The three-way split is a reliable quick check in Git interview questions.

What belongs in .gitignore, and why keep it at the repo root?

Answer: Build outputs, dependency directories, local environment files, editor and OS noise: anything reproducible or personal rather than source. Patterns match paths: /build targets the root only, build/ matches at any depth, *.log by extension, and a leading ! re-includes an exception. Commit the file at the root so the policy ships with the repo, and remember it does nothing for files Git already tracks, which is its own question below.

.gitignore is not working on a file. Why, and what is the fix?

Answer: Because ignore rules only affect untracked files. If the file was committed before the rule existed, Git keeps tracking every change to it. Fix: git rm --cached path untracks it while keeping the copy on disk, commit that, and the rule applies from then on. Naming the mechanism, tracking predates the rule, is the whole answer in Git interview questions; the command is just cleanup, and git check-ignore -v proves which rule fires.

What is the difference between a commit and a push?

Answer: git commit records a snapshot in your local repository; git push uploads your branch’s new commits to a remote and moves the remote branch forward. Nothing reaches teammates, review tools, or CI until the push. The separation is a feature: commit in small honest steps locally, then compose a clean shared history with rebase before anything goes public. That local-versus-public boundary reappears constantly in Git interview questions about undoing work.

What do git fetch and git pull do, and how do they differ?

Answer: git fetch downloads new commits and updates remote-tracking refs like origin/main, touching your branches and working tree not at all. git pull is fetch plus an integration step, merge or rebase, into the current branch. The safe habit: fetch, inspect with git log main..origin/main, then integrate deliberately. Pulling blind is how surprise merges and avoidable conflicts happen, which is the operational point this pair carries in Git interview questions.

What is origin?

Answer: Origin is the default nickname for the remote your clone came from, stored in config and listed by git remote -v. It is a name, not a special server: you can add more remotes, rename them, or repoint origin after a migration. Each remote keeps its own remote-tracking branches under refs/remotes, which is how your repository remembers the state of branches it does not own between fetches.

What is the difference between main and origin/main?

Answer: main is your local branch, which moves when you commit. origin/main is a remote-tracking bookmark of where main stood on the remote at your last fetch, and only fetch or pull moves it. They diverge constantly: ahead means unpushed commits, behind means unfetched ones. That distinction is the basis of ahead and behind counts, and of nearly every push-rejection diagnosis in scenario Git interview questions.

How do you create a branch and switch to it?

Answer: git switch -c feature/login creates the branch and moves to it in one step; plain git switch feature/login moves to an existing one. The older spellings, git checkout -b and git checkout, still work and still fill older runbooks. Both carry uncommitted changes across when nothing collides, which is convenient until it conflicts, and then the stash entry in this bank applies. Switch versus checkout is a small ladder rung that modern Git interview questions do check.

What is a fast-forward merge?

Answer: When the target branch has no commits of its own since the branch point, Git creates nothing: it slides the target branch pointer forward to your branch’s tip. History stays perfectly linear and no merge commit exists. Fast-forward is pure pointer movement, and it is the same finishing move rebase uses, which is why interviewers pair the two topics. Add that --no-ff forces a merge commit when a team wants integration points preserved.

What is a merge conflict, and why does it happen?

Answer: Git merges automatically whenever the two sides changed different regions of the files. A conflict happens when both sides changed the same lines since the common ancestor, or one side deleted what the other edited, because Git cannot choose between two humans’ intents. Conflicts are normal, not errors: they mean overlapping work, and resolving them is a decision only a person or a policy can make. That framing is what conflict questions in Git interview questions reward.

How do you resolve a simple conflict?

Answer: Git marks the contested region in the file between <<<<<<< HEAD and >>>>>>> feature, divided by =======. Edit to the content you actually want, remove the markers, git add the file, and commit to conclude the merge. git status lists whatever remains unresolved. Never commit marker lines, and note that CI pipelines grep for them, because a stray marker shipped to main is a real and recurring incident.

What does git merge –abort do?

Answer: It cancels an in-progress merge and restores the index and working tree to the state before you started. Use it mid-conflict when the resolution is over your head; nothing was recorded yet, so walking away is free. The sibling command git merge --quit clears the merge state but leaves conflicted files dirty, which is almost never what you want. Knowing the difference between the two is a small credibility win in Git interview questions.

What are tags, and how do lightweight and annotated tags differ?

Answer: A tag names one commit permanently: releases, milestones, deploy points. A lightweight tag is just the pointer, like a branch that will never move. An annotated tag is a real object storing tagger, date, and message, and it can be GPG signed, which is what release pipelines prefer. Pushes never carry tags by default, so ship them explicitly with git push origin v1.4 or --tags. Tag semantics feed directly into release-flavored Git interview questions.

What does git commit –amend do, and when is it safe?

Answer: It replaces the tip commit with a corrected one: --amend alone fixes the message, and staged changes get folded in. Mechanically it writes a brand new commit object with a new hash and moves the branch pointer, the old commit surviving in the reflog. Safe on unpushed commits. On pushed, shared ones it demands a force push, so prefer a follow-up commit or a revert, and say that boundary out loud in Git interview questions rather than waiting to be asked.

How do you throw away local edits to a single file?

Answer: git restore path, older spelling git checkout -- path, resets that file’s working-tree content to HEAD. It is unrecoverable: uncommitted changes never entered the object database, so there is no reflog trail. For a staged file, git restore --staged first to unstage, then restore the content. Anything you might want back goes through stash or a work-in-progress commit first, and saying so is the judgment layer Git interview questions listen for.

How do you undo the last commit but keep the changes?

Answer: git reset --soft HEAD~1 moves the branch back one commit and leaves the changes staged; --mixed, the default, unstages them as well; --hard deletes the changes from the working tree. Choose by where you want the work to land: soft for recommitting differently, mixed for restaging selectively, hard only when the work is truly unwanted, because hard is the one that needs the reflog if you were wrong. The three-mode comparison is a staple of Git interview questions.

What are Git’s three config levels?

Answer: System (/etc/gitconfig) for every user on the machine, global (~/.gitconfig) for you, and local (.git/config) for one repository, with local winning on conflicts. Inspect with git config --list --show-origin to see exactly which file supplied each value. The practical bite: user.name and user.email set correctly globally but wrong locally is why commits show a personal address on CI and review tools, a bug common enough that Git interview questions use it as a warm-up.

What are Git aliases?

Answer: Short names for long commands, stored in config: git config --global alias.lg "log --oneline --graph --decorate --all". They are personal, because they live in your config rather than the repo, so teammates are not forced into your habits. Common ones compress log views, undo flows, and staging. Interviewers read aliases as a signal of daily use; the honest caveat, which earns the credit, is that scripts and CI must always spell out the full commands.

What does git blame do?

Answer: It annotates each line of a file with the commit that last touched it: hash, author, date. Useful flags: -w to ignore whitespace churn, -C to follow lines that moved between files, -L 40,60 to scope a range. The discipline interviewers look for: blame finds the commit, then you read that commit in context, because the last toucher is often a reformat, not the real author. That read-the-context habit is the difference between blame as a tool and blame as an accusation.

What is a pull request?

Answer: A proposal to merge one branch into another, hosted by a platform like GitHub or GitLab: the diff, review comments, required status checks, and the merge button bundled into one reviewable unit. Locally nothing new happens; it is a collaboration layer over the same push and merge operations. Open small ones: small diffs get real reviews, giant ones get rubber stamps, and that observation is usually the follow-up Git interview questions are fishing for.

What makes a good commit message?

Answer: A short imperative subject under roughly 50 characters, a blank line, then a body explaining why the change exists, not what the diff shows, referencing the ticket when one exists. The test that matters: could a teammate skimming git log --oneline in six months reconstruct intent? Commit messages are the search index of a codebase, which makes this a quality question rather than a style question, and which is why it survives in Git interview questions year after year.

Why does Git not track empty directories?

Answer: Tree objects record files; directories exist only as path prefixes of files, so a directory containing nothing has nothing to point at. The convention is a placeholder file, usually .gitkeep, when structure itself matters, like mount points or required log directories. One sentence on the cause and one on the convention is a complete answer, and adding that this falls straight out of the snapshot model turns a trivia question into evidence you understand the object graph.

What is detached HEAD?

Answer: HEAD normally names a branch; detached, it points directly at a commit, so new commits land on no branch and become easy to lose when you switch away. It happens by design when you check out an old tag or hash to inspect history. Leave safely by naming a branch: git switch -c rescue. If you already switched and the commits are stranded, the reflog recovery question in the scenario tier of Git interview questions is your way back.

What is git stash?

Answer: It shelves uncommitted changes: git stash push saves modified tracked files and returns a clean working tree; git stash pop reapplies them. -u includes untracked files, git stash list shows the shelf, and pop drops the entry on success while apply keeps it. Stash is for minutes or hours, not days; for anything longer, a work-in-progress branch or a worktree is the honest answer, a boundary Git interview questions like you to draw.

What is a shallow clone?

Answer: A clone with truncated history, created with --depth 1 or --shallow-since. It downloads far less, which is why CI systems default to it. The cost: log, blame, and bisect only see the shallow slice, and pushing from a shallow clone is not supported. Unshallow with git fetch --unshallow when real history is needed, the step people forget when tooling that works locally fails in CI, which is exactly where shallow-clone Git interview questions are headed.

How does git mv differ from a plain mv?

Answer: git mv old new renames and stages in one step; a plain mv plus git add of both paths ends in the same place, because Git detects renames at diff time rather than recording them. Detection compares content similarity, with a threshold, so a light edit plus a move shows as a rename while a heavy rewrite plus a move shows as delete and add. That computed-rename detail is the part of this Git interview question that separates users from readers of documentation.

What does git remote -v show, and how do you manage remotes?

Answer: It lists configured remotes with their fetch and push URLs. Add one with git remote add name url, rename with git remote rename, update a moved server with git remote set-url, and clean stale branches with git fetch --prune. Multiple remotes are routine: origin plus an upstream in the fork workflow, or a mirror target for backup. Each remote name owns its own remote-tracking branches, which keeps their states independent, the detail interviewers want beyond the command list.

Intermediate Git interview questions

This tier is where Git interview questions stop testing vocabulary and start testing mechanism. Forty questions follow, and the pattern to internalize is command, then cause: name the tool, then explain which objects and refs it moves. That second half is what moves a candidate from operator to engineer in an interviewer’s notes, and it is the same habit the scenario tier of Git interview questions will expect under pressure.

Explain the four Git object types.

Answer: Git is a content-addressed object database with four types. A blob holds file bytes, nothing else. A tree lists directory entries: mode, name, and the blob or subtree each name points at. A commit points at one tree, lists parents, and carries author, committer, timestamps, and message. A tag object wraps another object with tagger, date, message, and an optional signature. Every object is named by the hash of its own content, so the graph is tamper-evident: change one byte anywhere and every hash above it changes. Prove it live with git cat-file -p HEAD^{tree} and git ls-tree HEAD.

Why are commit hashes immutable, and what does rewriting history break?

Answer: A commit’s hash is a function of its entire content: tree, parents, metadata, message. Nothing edits a commit in place; amend, rebase, and filter-repo write new objects with new hashes and move refs onto them, leaving the originals in the object store until garbage collection. What breaks: every clone holding the old commits now diverges from you, which is the entire risk model of rewriting shared history and the reason force-push policy exists. This mechanism sentence is the backbone of history-surgery Git interview questions.

What is the index, mechanically?

Answer: A single file, .git/index: a sorted list of path, mode, and blob hash, plus stat cache data to keep status fast. git add writes new blob objects into .git/objects and updates index entries; git commit serializes the whole index into one tree object. Checkout and merge rewrite index entries as they update the working tree. The index is not a diff or a patch list: it is a complete candidate tree, which is exactly why partial staging works at file and even hunk granularity.

What are refs, and what is packed-refs?

Answer: Refs are the naming layer over objects: branches under refs/heads, remote-tracking refs under refs/remotes, tags under refs/tags, plus special refs like HEAD, ORIG_HEAD, and FETCH_HEAD. Each is a tiny text file containing a hash. Once a repository grows thousands of them, Git consolidates them into one packed-refs file it reads transparently. This is why branch and tag creation cost one file write, and why almost every advanced Git operation reduces to deciding which refs to move where, the sentence interviewers want from Git interview questions on this topic.

What exactly does the reflog record, and how long does it live?

Answer: A local, append-only journal under .git/logs of every movement of HEAD and of each ref: commits, resets, rebases, checkouts, amends. Read it with git reflog, or per ref with git reflog show branch. Entries expire after 90 days by default, 30 days for unreachable commits, after which gc prunes the objects they point to. Two operational notes that senior Git interview questions probe: reflogs are per-clone and never pushed, so they rescue only work that existed on your machine, and recovery is time-boxed by that expiry.

What is a merge base, and how does a three-way merge use it?

Answer: The merge base is the best common ancestor of the two commits being merged. A three-way merge compares each side against that base: a change on one side applies cleanly, identical changes on both sides deduplicate, and overlapping edits with different results become conflicts. git merge-base A B names it. Every rule of merging, including why a rebased branch and its original fight each other, reduces to what each side did relative to the base, which is why this concept underpins so many Git interview questions.

What does a merge commit contain that a normal commit does not?

Answer: Two parents instead of one, plus the resolved tree, the snapshot after reconciliation. The two parents record exactly which histories were combined, which is what makes merge commits anchors for git log --graph, for bisect, and for revert, which needs both sides to compute an inverse. Their messages conventionally document the integration decision. Teams that squash every merge lose those anchors; that is a deliberate tradeoff when it is chosen, and an accident when it is not, and saying which is which scores in Git interview questions.

What does git rebase do, mechanically?

Answer: Rebase computes the commits your branch has that the target lacks, then replays them one at a time on top of the target. Each replay is a three-way merge using the original commit as one side, producing a brand new commit object with a new hash. The old commits survive until gc, reachable through the reflog, and the branch ref simply ends up pointing at the last replay. History reads linear; the hashes all change, which is the entire force-push conversation, and the sentence Git interview questions on rebase are built to elicit.

How do you choose between merge and rebase?

Answer: The golden rule: rebase commits you have not shared, merge everything else. Pull your own feature branch forward with rebase for a reviewable linear history; integrate two published branches with a merge so both sides’ history survives intact. Rebasing a shared branch rewrites history teammates already hold, and every clone after that pays for it. The phrasing that lands in Git interview questions: merge preserves reality, rebase curates it, and the choice is decided by who already has the commits.

What can interactive rebase do, command by command?

Answer: git rebase -i BASE opens an editable todo listing each commit in the range. The verbs: pick keeps it, reword edits its message, edit pauses so you can amend content, squash folds it into the previous commit keeping both messages, fixup folds discarding this message, drop removes it, and reordering lines reorders history. It is the tool that turns a week of WIP commits into a reviewable sequence, and git rebase --abort is always one command away, a safety fact worth stating in Git interview questions.

What are fixup commits and autosquash?

Answer: Commit a correction with git commit --fixup SHA, producing a commit whose message marks it as a fix for that commit. Later, git rebase -i --autosquash BASE reorders those fixes next to their targets and pre-selects fixup, so the todo needs no manual editing. The workflow turns oops commits into clean history without ceremony, and it is the daily-driver signal interviewers read in Git interview questions about history hygiene. Pair it with rebase.autoStash for a frictionless loop.

What does cherry-pick do, and where does it shine and bite?

Answer: It takes one commit’s diff and applies it as a new commit on your current branch: same changes, new hash, new parent. It shines lifting a hotfix from one branch to another without merging the whole branch, and rebuilding a branch from selected work. The bite: repeated cherry-picks across branches create duplicate content with different hashes, which later merges and confused humans both struggle with. -x records the source hash in the message, keeping the audit trail that follow-up Git interview questions always ask about.

What exactly do reset –soft, –mixed, and –hard move?

Answer: All three move the current branch ref to the target commit. --soft stops there: index and working tree untouched, changes reappear staged. --mixed, the default, also resets the index to the target, so changes reappear unstaged. --hard additionally rewrites the working tree from the target, and uncommitted work is gone from view, recoverable only through the reflog. The mnemonic worth saying aloud in Git interview questions: soft moves refs, mixed moves refs and index, hard moves all three.

When do you revert instead of reset?

Answer: Revert computes the inverse patch of a commit and commits it, so history grows instead of being rewritten. That makes it the only safe undo on pushed, shared branches: everyone holding the bad commit simply receives a second commit undoing it, no coordination required. Reset rewrites, and rewriting shared history strands every clone that pulled. The rule: a commit never pushed, reset freely; a commit on the remote, revert. One nuance senior answers add: reverting a merge commit requires -m 1 to say which parent to keep.

Undo a commit Pushed or shared? check git log origin/branch..branch no yes reset family –soft keeps staged, –mixed unstages, –hard rewrites tree, reflog is the net revert git revert SHA appends an inverse commit merge commits: git revert -m 1 SHA Rewrite what only you have; append an inverse for what others hold.
The undo funnel every recovery question reduces to: shared history is reverted, private history is reset.
Why did Git split checkout into switch and restore?

Answer: Checkout had accumulated three jobs, moving branches, detaching HEAD, and discarding file changes, and its flag grammar collided: git checkout -- path versus git checkout branch differ by two dashes and differ completely in effect. Git 2.23 split them: switch changes or creates branches, restore fixes files from any ref, defaulting to HEAD. The old command still works, but the split removed the classic footgun of one missing dash silently switching branches instead of restoring a file, which is the story Git interview questions on this topic want told.

What are ORIG_HEAD and MERGE_HEAD?

Answer: ORIG_HEAD is a safety bookmark written before dangerous ref moves: merge, rebase, and reset record where you were, so git reset --hard ORIG_HEAD is a one-step undo of the operation. MERGE_HEAD exists only during a conflicted merge and points at the commit being merged in; concluding the merge with a commit gives the result both parents, which is how two-parent history is created. Knowing these two special refs converts several panic scenarios into single commands, which is precisely why Git interview questions name them.

How does stash work under the hood?

Answer: Stash creates real commit objects: one for the working tree state and one for the index, merged into a commit with two parents that lands on the refs/stash stack, with older entries hanging off its parent chain. That is why stash pop can conflict like any merge, why git stash apply SHA works on any stash-shaped commit, and why a dropped stash is recoverable: the objects persist until gc, findable via git fsck --unreachable or the reflog of refs/stash. The internals answer is what separates this entry from the beginner one in Git interview questions.

What are Git hooks, and which ones matter most?

Answer: Scripts Git runs at fixed points, living in .git/hooks and activated by removing the .sample suffix. Client-side: pre-commit runs before the commit records and can reject it, commit-msg validates or rewrites messages, pre-push gates pushes, post-merge reinstalls or restarts after pulls. Server-side: pre-receive and update enforce policy on shared repos, which is what hosted platforms implement as protected branches and required checks. Hooks exit nonzero to abort, and they are plain executables in whatever the box speaks, facts Git interview questions treat as baseline.

How do you get hooks onto every developer’s machine?

Answer: .git is not cloned, so per-repo hooks do not travel with the code. The built-in answer is core.hooksPath: point it at a versioned directory, git config core.hooksPath .githooks, commit the scripts, and have each clone run that one-liner via a bootstrap or make init. Teams add a CI check that fails when hooks are not active. Naming the not-cloned problem plus the config key is the complete answer; naming a framework is optional garnish in Git interview questions.

What are submodules, mechanically?

Answer: A submodule entry in the superproject’s tree is a gitlink: a mode-160000 entry storing one commit hash of the child repository, alongside a .gitmodules file mapping name, path, and URL. The parent pins the child to an exact commit and tracks nothing else about it: not branches, not history. Clone and wire up with git submodule update --init --recursive; bump the pin by updating the child, then committing the gitlink change in the parent. The pointer-only model is the mechanism Git interview questions on submodules are checking.

What goes wrong with submodules in practice, and what are the alternatives?

Answer: The classic failures: clones arrive with empty submodule directories because update --init was skipped; CI builds the wrong child version because someone pushed the parent’s new pin before pushing the child commit it names; and detached HEADs inside submodules trap people into committing on no branch. Alternatives: subtree merges fold the child’s history into the parent, vendoring copies source at a pinned version, and package managers cover the pure dependency case. Each trades one pain for another, and naming which pain you are buying is the senior move in Git interview questions here.

What are worktrees, and when do they beat stashing?

Answer: git worktree add ../hotfix main checks a second branch out into a separate directory while both share one object database and ref set. Two branches are simultaneously checked out, so switching context is a cd, not a stash-and-pray. Use them to review a colleague’s branch without wrecking your own state, run a long build on one branch while coding another, and hold parallel release maintenance. The one rule: the same branch cannot be checked out in two worktrees at once, and citing that rule is how Git interview questions here are won.

How does git bisect work?

Answer: Binary search over history, guided by a predicate. git bisect start, mark git bisect bad at the broken commit and git bisect good at a known-working one; Git checks out the midpoint, you answer bad or good, and the range halves each round, converging in log2 steps, a thousand commits in about ten tests. git bisect run cmd automates the loop with any command whose exit code answers the question, zero for good, nonzero for bad. Close with git bisect reset to return where you were, the step forgotten in half of all bisect Git interview questions.

What is git describe for?

Answer: It names a commit relative to the nearest annotated tag: v2.1.0 means exactly the tag, v2.1.0-3-g1a2b3c4 means three commits after it at that hash. CI and release pipelines use it to stamp build versions that are both human-readable and traceable to an exact commit, which makes rollbacks and incident reports unambiguous. It needs real history and real tags, which is precisely why shallow CI clones break describe and force the fetch-depth fix, the pairing Git interview questions love on this topic.

What happens when a pull meets a diverged branch?

Answer: Your branch and its upstream both gained commits, so a plain pull must invent an integration. Modern Git refuses to guess: it errors and asks you to configure pull.rebase or pull.ff. pull.rebase true replays your local commits on top of upstream for linear history; pull.ff only refuses to merge at all; the legacy default creates a merge commit. The senior habit: configure pulls once, explicitly, and know which mode your team standardized on, because surprise merge commits from pull are a classic history mess that Git interview questions use as a war-story filter.

What does –force-with-lease do that –force does not?

Answer: A plain force push overwrites the remote branch regardless of what landed there since your last fetch. --force-with-lease adds a precondition: the remote branch must still sit at exactly the commit your remote-tracking ref remembers, or the push is rejected. If a teammate pushed inside that window, the lease fails and their work survives. It is the default-safe spelling for pushing rebased branches; the residual risk is a stale remote-tracking ref from an old fetch, which is why the rule is fetch immediately before any lease-checked force push, the sentence Git interview questions on this topic exist to hear.

What is rerere?

Answer: Reuse recorded resolution: enable with git config --global rerere.enabled true, and Git records how you resolve each conflict hunk, then replays that resolution automatically when the identical conflict reappears. It shines on long-lived rebase retries, repeated merges of the same branches, and teams reworking the same pull requests over days. The caveat worth stating: recorded resolutions replay without asking, so a bad one must be cleared deliberately, or the same mistake returns silently every time, a detail that turns a config answer into a real one in Git interview questions.

What are refspecs?

Answer: The source-to-destination patterns behind every fetch and push: git push origin HEAD:refs/heads/feature/x pushes your current commit to a differently named remote branch, +refs/heads/*:refs/remotes/origin/* is the default fetch mapping, with the leading plus meaning allow non-fast-forward updates. Practical uses: publish a local branch under a new name on the remote, delete a remote ref with an empty source, and fetch a pull request head like refs/pull/42/head for local review before approving it. Refspec fluency is the mark of someone who has debugged pipelines, which is why advanced Git interview questions reach for it.

Why does a push get rejected as non-fast-forward?

Answer: The remote branch holds commits your branch does not, and Git refuses to move that branch pointer backwards or sideways, because from the remote’s perspective doing so would discard someone’s commits. Fetch, look at what landed there with git log --oneline HEAD..origin/branch, then integrate: rebase your work on top or merge, and push again. Overriding legitimately requires rewriting your own branch and force-pushing, ideally with a lease, plus agreement from whoever owns the branch. Explaining the refusal as pointer safety is the answer Git interview questions grade here.

What does git gc do, and what are packfiles?

Answer: Loose objects, one file per object, get compressed into packfiles: single files holding many objects with delta compression against similar content, plus an index for lookup. git gc runs the housekeeping: packs loose objects, prunes unreachable ones past the grace period, expires old reflog entries per policy, and repacks for locality. Modern Git auto-maintains in the background, so manual gc matters mostly after history surgery or on giant repositories where an aggressive repack is a maintenance window, not a keystroke. That operational framing is what Git interview questions on gc are listening for.

What is .gitattributes for?

Answer: Per-path attribute rules committed with the repo: text versus binary handling, end-of-line normalization, custom diff and merge drivers, export-ignore for archives, and language statistics hints. Unlike per-user config, it applies to everyone who clones, which is what makes it policy rather than preference. The highest-value lines in mixed teams pin line endings per file type, like *.sh text eol=lf and *.ps1 text eol=crlf, and declaring generated files with a merge driver keeps them out of conflict marathons, both common follow-ups in Git interview questions.

How do line endings stay sane across platforms?

Answer: Repositories store LF. core.autocrlf controls working-tree conversion: true converts to CRLF on checkout and back on commit, suiting Windows; input converts on commit only, the usual Linux and macOS choice; false leaves files alone and lets .gitattributes decide. After changing policy, renormalize once with git add --renormalize . and commit the result. The failure this prevents, files flipping to modified on every checkout and diffs full of invisible churn, is the exact story the scenario tier of Git interview questions stages later.

What is Git LFS, and when do you need it?

Answer: Large File Storage replaces big binaries in history with tiny pointer files while the actual bytes live on an LFS server, fetched on demand by the filters installed with git lfs install. Track patterns with git lfs track "*.psd", which writes the .gitattributes rules. Reach for it with assets in the tens of megabytes and up, model weights, media, datasets. It fixes clone size and push limits and adds a dependency: every clone and CI job needs the client, and forgetting it yields pointer files where content should be, the classic LFS failure named in Git interview questions.

How does commit signing work?

Answer: git commit -S signs with GPG, or with SSH keys after git config gpg.format ssh and a signingkey entry; git log --show-signature verifies. Platforms show a verified badge once the public key is registered, and branch protection can require signed commits. The operational value is provenance for review and release: a tag’s signature proves who produced the release, and commit signatures prove the pusher is who the history claims. Rotation is the caveat: old signatures verify only while their keys remain trusted, the follow-up Git interview questions attach here.

What are the implications of shallow clones in CI?

Answer: Depth-one clones are fast and fine for build-and-test, but git describe, blame, changelog generation, bisect, and merge-base checks all need more history. The symptoms are specific: describe returns nothing useful, blame claims the file has no history, rebase jobs cannot find a merge base. Fix per job: full fetch-depth: 0 for version, changelog, and merge automation, shallow for plain builds, or a bounded middle with --shallow-since. Declaring per-job depth is the answer; blanket full clones just relocate the slowness, and saying so is the scoring point in these Git interview questions.

What are sparse-checkout and partial clone?

Answer: Both shrink work in huge repositories. Sparse-checkout limits which paths the working tree materializes: git sparse-checkout set services/a services/b, while the full object database stays local. Partial clone goes further: git clone --filter=blob:none fetches commits and trees but defers blobs until checkout actually needs them. Monorepos combine the two to give teams fast clones of their slice. The caveat: any tool that assumes whole-tree visibility, global grep, some linters and codegen, pays for what the clone skipped, and naming that caveat is the senior half of this Git interview question.

Monorepo or multirepo: how do you choose?

Answer: Monorepo: one repository, one history, atomic cross-service changes, unified tooling and CI, at the cost of scale engineering, partial clones, path-based CI triggers, and coarse access control. Multirepo: independent lifecycles, small clones, clear ownership, at the cost of coordination, version pinning between services, cross-repo changes become release dances, and discoverability suffers. A monorepo earns its keep when services change together often and the tooling investment is real; otherwise multirepo’s simplicity wins. It arrives as a discussion question, and the honest tradeoff framing is what Git interview questions on repository topology reward.

Squash, merge, or rebase-and-merge for pull requests?

Answer: A merge commit preserves the branch’s real history and adds an integration anchor. Squash collapses the branch into one commit titled with the pull request, giving perfectly linear history but destroying intermediate commits and authorship granularity. Rebase-and-merge replays the branch’s commits linearly without a merge commit. Teams choose by culture: squash when the unit of revert is the feature, merge when intermediate history matters, rebase for linear purists who still want commit granularity. Naming the unit-of-revert consequence is the sentence that scores in Git interview questions on workflow policy.

Trunk-based development or long-lived branches?

Answer: Trunk-based: everyone integrates to main frequently, branches live hours or days, feature flags gate incomplete work, and conflicts stay small because divergence stays small. Long-lived models like GitFlow carry release branches and merge overhead, and integration pain arrives in bulk at merge time. Continuous delivery pushes teams toward trunk-based plus flags; regulated release trains sometimes justify branches, and saying when is the nuance. What interviewers probe: how incomplete features coexist with an always-releasable main, and the answer is flags, not feature branches that live for months, which is the conclusion Git interview questions on branching strategy steer toward.

What do the ours and theirs merge strategies really do?

Answer: With -X ours and -X theirs, conflicts resolve favoring one side per hunk while non-conflicting changes from both sides still merge, and the names are relative to whichever side you are standing on. With -s ours, the strategy ignores their changes entirely: it records a merge whose tree is yours alone, adopting nothing. Confusing -X with -s is how teams silently discard an entire branch’s work while the log claims it was merged, and that trap is exactly why this question appears in senior Git interview questions.

Scenario and troubleshooting Git interview questions

The final tier is the live round: symptom first, recovery second, judgment throughout. Every answer below states a diagnostic order and the reasoning behind it, because scenario Git interview questions are graded on the order, not on luck. Rehearse them out loud until the sequence, establish what is shared, reach for the reflog, choose the least destructive tool, is reflex.

You committed to main instead of a feature branch, and have not pushed. Fix it.

Answer: Order: confirm nothing is shared, git status then git log origin/main..main to see exactly which commits are local only. Cut the branch where the work sits: git branch feature/x, rewind main to the remote with git reset --hard origin/main, then git switch feature/x and keep working. If good commits came after the bad ones, cherry-pick those onto the new branch first, then reset. Nothing shared changed, so no coordination is needed; the only rule is verifying the not-pushed claim before any reset, the verification step scenario Git interview questions always score.

You pushed a broken commit to a shared branch. What now?

Answer: Decide intent first: does the fix go forward, or must the bad change leave history? A forward fix, commit the correction, is normal, boring, and usually right when the damage is functional but harmless to history. Removing it from shared history means revert, which appends an inverse commit and is safe for every clone, or a force-pushed rewrite, which strands everyone who pulled and requires coordination. On protected branches the decision is usually made for you: revert. Saying revert before being prompted is the pass condition in this family of scenario Git interview questions.

git reset –hard just ate your work. Recover it.

Answer: Stop making changes; nothing is deleted, the commits are merely unreachable. git reflog lists every recent HEAD position with hashes; find the entry from before the reset, then git reset --hard HEAD@{n} to return, or git branch rescue HASH to name the tip without moving anything. The window: objects survive until gc prunes unreachable ones, typically weeks. Then redo the intended operation with soft or mixed instead of hard, so a mistake lands in the working tree instead of vanishing. The reflog answers half of all lost-work Git interview questions because it records every move HEAD ever made.

A teammate deleted a branch that held unmerged commits. Recover them.

Answer: The commits are unreachable from refs but still present in every clone that fetched them, until gc. On your machine: git reflog shows checkouts and pulls involving that branch, and git fsck --unreachable lists orphaned commits directly; the tip often also survives as a remote-tracking ref or on the platform’s merged-pull-request page. Restore with git branch name HASH, then push it or open a pull request so recovery stops depending on local clones, which expire. Naming fsck as the no-reflog fallback is the detail that elevates this answer in Git interview questions.

An interactive rebase exploded halfway through. Get out safely.

Answer: Two exits, chosen by intent. Abort: git rebase --abort returns branch and working tree to the exact pre-rebase state, which Git recorded in ORIG_HEAD and the reflog. Continue: resolve the current conflict, git add it, git rebase --continue, and repeat per replayed commit. The traps: starting a second rebase while one is mid-flight, and fixing things by hand inside .git/rebase-merge; git status reports the rebase state, so read it before acting. If abort somehow fails, the pre-rebase reflog entry is the hard fallback, and saying that fallback is what scenario Git interview questions listen for.

Detached HEAD panic: you made three commits while detached, then switched to main. Where did they go?

Answer: Nothing is lost yet: switching only moved HEAD, and the commits remain in the object store. Find them with git reflog, which logged every position, or git fsck --unreachable if the reflog is unhelpful, then reattach: git branch rescue HASH or git switch -c rescue HASH. The lesson to state while recovering: detached HEAD is safe for reading and hostile for writing, and any commits made there need a branch name before you wander off. This exact walk-away is one of the most common scenario Git interview questions because everyone does it once.

Someone force-pushed main, and your local main now diverges from origin. Reconcile.

Answer: Fetch first and look at both worlds: git fetch, then git log --oneline main..origin/main and its reverse, or git log --graph --all --oneline, to see both versions of history. Decide what to salvage from the old line: anything valuable lives in your local pre-rewrite commits. Rebuild on the new base: rebase your unique work with git rebase --onto origin/main, or for a clean slate git reset --hard origin/main and reapply. Never force-push your stale main back; that merely reverses their rewrite and deepens the mess. Coordinating with whoever rewrote is the closing step interviewers want in these Git interview questions.

Your push is rejected: non-fast-forward on your feature branch. Walk the order.

Answer: Read the rejection, then fetch and inspect before touching anything: git fetch, then git log --oneline HEAD..origin/feature shows what the remote has that you lack. Integrate deliberately: rebase your commits on top, resolving conflicts one commit at a time for a clean review, or merge if the branch is shared. Re-run the tests, then push. A force push is correct only when the remote commits are known garbage, typically your own pre-rebase leftovers, and then only with --force-with-lease. Fetch, inspect, integrate, push: that order is the graded content of these Git interview questions.

An API key was pushed and the repository is public. Give the full response.

Answer: Rotate the credential first, immediately, before any Git work: the history is already cloned somewhere, so removal is secondary to invalidation. Then rewrite history with git filter-repo, the maintained successor to filter-branch: git filter-repo --replace-text expressions.txt scrubs the string from every commit and produces new hashes throughout. Force-push all branches and tags with --force-with-lease, have the team re-clone rather than pull, and audit access and platform logs for the window the key was live. Secret-purge Git interview questions always start with rotation; candidates who open with rewriting fail the judgment half.

1. Rotate invalidate the key before any Git work 2. Rewrite git filter-repo –replace-text 3. Republish force-push branches and tags, with lease 4. Re-clone team gets fresh clones, logs audited Leaked secret: the response pipeline Rotation first: every old clone and platform cache still holds the secret until the key is dead. New hashes mean every teammate re-clones; pulls from stale history resurrect the leak.
The secret-in-history pipeline: rotate, rewrite with filter-repo, force-push with a lease, and re-clone the team.
A 2 GB build artifact was committed, and pushes now fail while clones crawl. Fix it.

Answer: If the file is in pushed history, config tweaks do nothing: history surgery is required. git filter-repo --strip-blobs-bigger-than 10M, or a path-based removal, rewrites every commit; force-push with coordination, and accept that the team re-clones. Going forward: ignore the artifact path, move binaries to LFS or artifact storage, and add a pre-receive size cap so the next giant blob is rejected at push time instead of at clone time. Platform-side caches can hold the old objects for a while, which is why clone sizes sometimes lag the fix, a real-world note Git interview questions reward.

A merge has conflicts in 40 files. Give the marathon strategy.

Answer: Sequence it. First set merge.conflictStyle zdiff3, which shows the common ancestor above the two sides and usually makes the right answer obvious. Then triage git status: resolve whole categories mechanically with git checkout --ours path or --theirs path for generated files, hand-resolve only the load-bearing source files, and enable rerere in case the merge gets retried. Commit when status is clean and tests pass. Aborting is a legitimate outcome when intent is unclear, and saying so, rather than heroically guessing, is the judgment layer these scenario Git interview questions exist to test.

A conflict was resolved wrongly, and the merge is already committed and pushed. Fix it.

Answer: Scope the damage first: git show on the merge commit, or git log --cc -1, shows what the resolution actually chose. If real changes were dropped, fix forward: git revert -m 1 MERGE_SHA to undo the merge, then re-merge correctly, resolve again, and push. On unshared history, redo it entirely with reset and a fresh merge instead. The named trap to volunteer: reverting a merge and later re-merging the same branch silently drops those changes again unless the revert is reverted first, and that trap is a senior-level favorite in Git interview questions.

A bad merge was reverted months ago; re-merging the branch now does nothing. Why?

Answer: Git compares against history it believes it already has: the revert commit is a descendant of the merge, so the changes read as already applied, and the new merge brings nothing. The fix is to revert the revert: git revert REVERT_SHA, which reapplies the original changes as new commits, after which the branch merges normally. This revert-the-revert dance is famous enough that senior Git interview questions use it to test merge-base reasoning rather than memorized commands, and candidates who narrate why, instead of just naming it, close the round.

Production broke and nobody knows which commit did it. Find it.

Answer: Anchor a known-good point first: the last deploy tag or a green CI run. Then git bisect start, mark git bisect bad at current main, git bisect good v2.3.0, and answer each midpoint, or automate with git bisect run make test, exit zero meaning good. The range halves each round, a hundred commits in about seven steps. Confirm the culprit by reverting it locally and rerunning the failing check, then revert on main with the bisect log attached for the postmortem, saved with git bisect log, and always finish with git bisect reset.

500 commits 250 125 63 1 test test test test git bisect: log2 steps to the culprit Each test halves the range: 500 commits fall to one in about nine tests. git bisect run automates the loop with any command whose exit code answers bad or good.
Bisect as a funnel: each midpoint test halves the suspect range, so even huge histories converge in a handful of steps.
CI fails with strange Git errors after someone “optimized” the checkout. Diagnose.

Answer: Treat it as shallow-clone symptoms until proven otherwise: git describe returns nothing useful, blame claims files have no history, rebase automation cannot find a merge base, changelog steps see no tags. Compare the CI checkout config against local reality: fetch depth, tag fetching, and whether that job needs history at all. Fix per job: fetch-depth: 0 for version and merge automation, shallow for plain builds. The lesson to narrate in these Git interview questions: shallow clones change what Git knows, and every history-reading tool downstream inherits the amnesia.

git stash pop hit conflicts, and now the stash looks gone and the tree is a mess. Recover.

Answer: Order: pop applies and drops only on success; on conflict it keeps the entry, so run git stash list before assuming loss. A genuinely dropped stash is recoverable while its objects live: git fsck --unreachable surfaces stash-shaped commits, or check the reflog of refs/stash, then git stash apply SHA. For the messy tree, resolve like any merge conflict, or git reset --hard and reapply from the recovered stash. Then change the habit: apply, verify, drop deliberately, because pop’s auto-drop is the trap this scenario Git interview question is really about.

Half a feature is done, and an urgent hotfix is needed on main. Options, in order?

Answer: Judge by the state of the work. Uncommitted and small: git stash push -u, fix on main, pop after, resolving any conflicts. Anything nontrivial: commit the work in progress to the feature branch first, safer and reviewable later with autosquash. If the hotfix itself will take a while, git worktree add a second checkout of main and fix there without touching your state at all. Name the anti-pattern too: committing half-broken code straight to main to hold it, which poisons every bisect and every teammate, a habit scenario Git interview questions exist to catch.

Files flip to modified after every checkout, on every machine. Line-ending churn: fix it.

Answer: Confirm the churn is whole-file: git diff shows every line changed or nothing visible, which is eol noise, not content. Normalize in order: add a .gitattributes declaring text handling per file type, set core.autocrlf input on Unix CI, run git add --renormalize ., and commit once; then everyone re-clones or resets cleanly so local caches agree. The diagnosis to state: the index and working tree disagree about bytes, and the cure is one committed policy file plus a single renormalize commit, not every developer’s local config, which is the conclusion these Git interview questions are steering toward.

A file shows as modified with a zero-line diff. What is it?

Answer: A mode change, usually the executable bit flipped by a tool or by a filesystem that does not preserve permissions, common on Windows mounts and some CI volumes. git diff prints old mode and new mode lines as the only change. If the bit is meaningless for your team, set core.fileMode false so Git ignores mode churn; if it matters, chmod deliberately and commit it. A fifteen-second answer, and the zero-diff modified file is a durable favorite in scenario Git interview questions because it looks like corruption and is not.

git status says you are in the middle of a merge, and nothing you do clears it.

Answer: That state lives in MERGE_HEAD: the merge concludes only by committing the resolution or aborting cleanly with git merge --abort. Diagnose with git status before acting: staged files present means finish with a commit; chaos or half-applied state means git merge --quit, which clears the merge state and leaves the tree as it stands, then repair deliberately. Never delete files under .git by hand to force it, because that trades one confusing state for a worse one, and refusing to do so is the discipline these Git interview questions check.

A tag went out pointing at the wrong commit, or should not exist. Fix the remote.

Answer: Tags are refs, so the mechanics are a push deletion plus a re-push: git push --delete origin v1.2, recreate or move the tag locally, push it again. The judgment half matters more: if releases, pinfiles, or artifacts consumed the tag, deleting it rewrites published truth, so prefer a new tag, v1.2.1, and let the bad one die. Also say the blast radius: re-pushing the same tag name breaks every clone and mirror that trusted tag immutability, which is why release-process Git interview questions probe the judgment before the commands.

After a teammate rebased their pushed branch, your log shows duplicate commits. What is true, and what do you do?

Answer: Both sets are real: the rebase created new hashes carrying identical changes, and anyone holding the pre-rebase refs sees both. Verify equivalence with git cherry -v or git range-diff base..old-tip base..new-tip, which pairs commits by patch and shows what survived. Then converge: fetch, rebase your local work onto their rewritten tip, drop stale remote-tracking state with git fetch --prune, and re-push with a lease if you own the branch. The team rule worth proposing: announce shared-branch rebases, the policy note that lifts this answer above mechanics in Git interview questions.

The monorepo takes twenty minutes to clone, and CI burns hours a day on it. Speed it up.

Answer: Measure which cost dominates first: transfer, checkout, or history operations. Then apply in order: shallow fetch with depth for build jobs, sparse-checkout so jobs materialize only their service paths, and partial clone with a blob filter so unneeded blobs never transfer. Keep full clones for release and history jobs. Name the tradeoffs: shallow clones lose describe and bisect, sparse setups break whole-tree tooling, and each job should declare what it needs instead of inheriting a blanket config. Repository topology plus per-job depth is the pairing these monorepo Git interview questions expect.

The submodule directory is empty in CI and the build fails. Fix the pipeline.

Answer: The submodule was never materialized: clones do not fetch submodule content automatically. Order: add git submodule update --init --recursive to the checkout steps, verify the pin with git submodule status, and confirm the pinned child commit actually exists on the child’s remote, because the parent stores only a hash. Second-order failure to know: the pin points at a commit that lived only on a departed developer’s machine, which no amount of updating fixes until someone re-pins to a pushed commit, the edge case that separates experienced answers in these Git interview questions.

Every Git command in one repository takes seconds; status is slow enough to hurt. Diagnose.

Answer: Measure first: GIT_TRACE_PERFORMANCE=1 git status names the slow phase. Usual causes at scale: millions of loose objects awaiting gc, a huge index from a pathologically wide tree, untracked-file scanning over generated directories, and on Windows, antivirus scanning .git in real time. Fixes: run git gc or let background maintenance own it, enable the untracked cache and fsmonitor features, mark generated paths ignored, and exclude .git from real-time scanning. Naming a measurement flag plus two causes and one fix each is the passing bar for performance-flavored Git interview questions like this one.

A cleanup script rewrote main’s history, and half the team has pushed since. Walk the recovery.

Answer: Freeze pushes first, an announce-and-hold window, because every further push deepens the divergence. Map old to new: the rewriter publishes the intended new tips, ideally with verification hashes. Each developer then: fetch, rebase each local branch onto the new tip, drop the stale duplicates, verify content survived with git range-diff, and re-push with --force-with-lease under the freeze; anyone with uncommitted work stashes first. Close with the policy lesson: history rewrites require a freeze, an announcement, and lease-checked force pushes, or this scenario repeats, which is the takeaway Git interview questions on team recovery want stated.

Hands-on scenario labs

Reading answers builds vocabulary; recovery under pressure needs reflexes, and scenario Git interview questions are graded on reflexes. Each lab below is a safe, self-inflicted incident in a throwaway repository. Do each one three times: once with the checklist open, once from memory, once narrating out loud as if an interviewer were listening. That narration is exactly the rehearsal these rounds reward.

Lab 1: break a branch and recover it with the reflog

  • Create a scratch repo and five commits: git init lab1 && cd lab1, then repeat echo $n > file.txt && git add . && git commit -m "c$n".
  • Note the tip hash with git log --oneline -1, then destroy the top: git reset --hard HEAD~2, and confirm the log is shorter.
  • Recover: git reflog to find the pre-reset entry, then git branch recovered HEAD@{1} and inspect it with git log --oneline recovered.
  • Repeat the destruction on purpose, this time recovering with git fsck --unreachable instead of the reflog, and compare what each shows.
  • Clean up deliberately: git branch -D recovered, then find the stranded commits again once, so the recover-from-anything loop is muscle memory.

Lab 2: stage a merge conflict and resolve it twice

  • Set git config merge.conflictStyle zdiff3 and git config rerere.enabled true in the scratch repo before starting.
  • Create two branches editing the same line of one file, merge one into the other, and read the conflict block, including the ancestor section zdiff3 shows.
  • Resolve by hand, git add, commit, then git reset --hard HEAD~1 and re-merge to watch rerere replay your recorded resolution automatically.
  • Break it on purpose: accept a wrong resolution, commit, then undo the pair with git revert and observe the history both versions leave behind.
  • Finish by aborting a fresh conflict with git merge --abort and confirming git status is spotless afterward.

Lab 3: rebase surgery and lease-checked force pushes

  • Build a messy branch: a typo-fix commit, a WIP commit, and a duplicate fix, then run git rebase -i --autosquash against the base and clean it with fixup, squash, and reword.
  • Verify nothing was lost: git range-diff base..old-tip base..new-tip after saving the old tip in a branch first, and read the pairing output.
  • Push the cleaned branch to a toy remote, amend one commit, and re-push with git push --force-with-lease to see a lease-checked overwrite succeed.
  • Simulate a teammate: push to the same branch from a second clone, then repeat the lease push from the first and watch it fail, which is the safety net working.
  • Close by narrating the golden rule out loud: private history rebases, shared history reverts, force pushes always lease-checked.

Cheat sheet: the commands behind the answers

Nearly every item in this bank of Git interview questions resolves to one of the commands below, in the same order you would reach for them live. Learn the table, then attach one sentence of mechanism to each row, and the scenario round becomes a checklist instead of a gamble.

CommandWhat it tells you or does
git statusBranch, staged, unstaged, untracked, and any in-progress merge or rebase; the opening move
git log --oneline --graph --all --decorateReal topology of refs and commits; every divergence question starts here
git diff --stagedExactly what the next commit will contain
git add -pHunk-by-hunk staging for atomic commits
git commit --amendReplace the tip commit; unpushed only
git reset --soft | --mixed | --hardMove branch, plus index, plus worktree, in that order of destruction
git revert SHASafe undo on shared history; -m 1 for merge commits
git restore --staged path / git restore pathUnstage, then discard working-tree changes
git switch -c branchCreate and move; the modern branch changer
git stash push -u / pop / listShelve work including untracked files; apply-verify-drop is the safe loop
git reflogEvery move of HEAD; the recovery index for resets, rebases, and amends
git fsck --unreachableOrphaned commits with no reflog path; last-resort recovery
git cherry-pick SHALift one commit onto the current branch; -x keeps provenance
git rebase -i --autosquash BASEInteractive history cleanup with fixup pairing
git merge --abort / git rebase --abortWalk away from any in-progress integration, free of charge
git bisect start / bad / good / run / resetBinary search to the culprit; run automates it
git blame -C -w -L 40,60 fileLine provenance, whitespace-proof, move-aware, range-scoped
git worktree add ../dir branchSecond checkout, shared object store; context switch by cd
git submodule update --init --recursiveMaterialize pinned child repos; the CI checkout fix
git push --force-with-leaseForce push that refuses to erase teammates’ fresh work
git fetch --pruneSync remote-tracking state and drop deleted remote branches
git range-diff base..old base..newProve a rebase changed nothing, commit by commit
git filter-repo --replace-text rules.txtWhole-history surgery for secrets and giant blobs
git sparse-checkout set pathsMaterialize a slice of a monorepo; pairs with partial clone filters

The authoritative reference for every command here is the official Git documentation, and the free Pro Git book covers the internals behind the intermediate tier in more depth than most interviews will ever need.

Key takeaways and FAQ

The through-line of every tier above: Git interview questions reward candidates who pair a command with the mechanism underneath it. The command alone reads as memorization; the mechanism alone reads as theory; together they read as someone who has recovered a broken repository at 2 a.m. and can prove it. Every recovery reduces to the same three moves: establish what is shared, consult the reflog, choose the least destructive tool.

How long should I prepare for Git interview questions?

With daily Git use, a focused week: two days speaking the beginner tier aloud, two on the intermediate mechanisms, one on scenarios, the weekend on the labs. Without daily use, plan three weeks and run every command in a scratch repo yourself, because fingers remember what eyes skim. Git interview questions punish recitation, so rehearse answers as sentences, not lists.

Are Git interview questions different for DevOps and SRE roles?

The beginner and intermediate tiers are identical; the scenario emphasis moves. DevOps loops lean toward hooks, CI clone mechanics, monorepo tooling, and branch protection, while SRE loops add bisect under incident pressure and recovery choreography. Prepare the full bank either way, because panel composition is unpredictable and cross-training is cheap.

Which Git topics come up most in Git interview questions?

By real frequency: reset versus revert, merge versus rebase, fetch versus pull, reflog recovery, conflict resolution, and force-push safety. Master those six and their follow-ups, and you can handle the large majority of rounds. The scenario tier of Git interview questions is mostly those six topics wearing symptoms.

Do Git interview questions include live terminal work?

Increasingly yes, against a sandbox repository, especially for platform and infrastructure roles. The labs on this page are built for that format, and practicing spoken narration while typing is the single best rehearsal. Interviewers grade the diagnostic order as much as the outcome, so say your steps while you type them.

How do I practice dangerous Git operations safely?

In a scratch repository that costs nothing: init a folder, make commits, and break it on purpose. Resets, rebases, force pushes with a lease, filter-repo dry runs, and bisect all behave identically in a toy repo. The reflog will save you there exactly as it would at work, which is the entire point of rehearsing in Git interview questions conditions before the real one.

What should I read after this page?

Continue with the Linux interview questions and Kubernetes interview questions banks, since Git workflows sit directly beside the command-line and pipeline skills those pages drill, then browse the Docker interview questions bank, the software development interview questions bank for the SDLC and code-review practices around commits, and the DevOps Prep hub for the rest of the series.

Git Prep Quiz: Recovery, Rebase, and Force-Push Safety

1 / 5

Your push --force-with-lease was rejected even though you were sure the branch was yours. Why?

2 / 5

When does git merge create a merge commit instead of fast-forwarding?

3 / 5

What does a branch actually contain on disk?

4 / 5

git reset --hard HEAD~2 just destroyed two commits you had not pushed. What is the recovery path?

5 / 5

A bad commit is already on a shared branch that teammates have pulled. What is the safe undo?

0%