Git Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What does
git rebase maindo on a feature branch?Correct answer: Replays the branch's commits on top of the latest
mainEach feature commit is re-applied on the new base, producing new commits with new hashes. The result is a linear history, as if you had started the branch from today's
main.2. What is the "golden rule" of rebasing?
Correct answer: Don't rebase commits that others have based work on
Rebasing replaces commits with new ones. If teammates already have the old ones, their history diverges and they end up with duplicates. Your own unpushed or private branch is fine to rebase.
3. Merge vs rebase for integrating
maininto a feature branch: what's the trade-off?Correct answer: Merge keeps true history; rebase gives a linear one but rewrites commits
Merge preserves exactly what happened and adds merge commits; rebase produces a clean line that's easier to read and bisect, at the cost of new hashes. Teams pick one convention.
4. During a rebase you hit a conflict. What's the usual sequence?
Correct answer: Fix the files,
git addthem, thengit rebase --continueRebase stops on the commit that conflicts; once resolved and staged,
--continuemoves to the next one.--skipdrops the current commit entirely,--abortrestores the original branch.5. What can
git rebase -i HEAD~4do?Correct answer: Reorder, squash, reword or drop the last 4 commits
Interactive rebase opens a todo list with
pick,reword,squash,fixup,editanddrop. It's the standard way to tidy a branch before opening a pull request.6. What is the difference between
squashandfixupin interactive rebase?Correct answer: Both combine commits;
fixupdiscards the folded commit's messagesquashlets you edit a combined message,fixupkeeps only the earlier commit's message.git commit --fixup <hash>plusrebase -i --autosquashplaces them automatically.7. What does
git cherry-pick <hash>do?Correct answer: Applies that commit's changes as a new commit here
The original commit stays where it was; you get a copy with a new hash. A typical use is backporting a fix from
mainto a release branch.8. You ran
git reset --hardand lost a commit. How can you get it back?Correct answer: Find it in
git reflogand reset or branch to itThe reflog records every position
HEADand branches had locally, usually for 90 days.git branch rescue <hash>brings the commit back.9. What is the default mode of
git reset <commit>?Correct answer:
--mixed: moves the branch and resets the index, keeps filesMixed leaves your changes in the working tree as unstaged.
--softkeeps them staged,--harddiscards them.10. Why prefer
git push --force-with-leaseover--force?Correct answer: It refuses to overwrite remote commits you haven't seen
--forcereplaces the remote branch blindly, wiping a colleague's new commits.--force-with-leasechecks that the remote is still where your last fetch saw it.11. How do you undo a merge commit that was already pushed to
main?Correct answer:
git revert -m 1 <merge>to undo it relative to the first parentA merge has two parents, so revert needs
-mto know which side is the mainline. Note that re-merging the same branch later won't bring the reverted changes back unless you revert the revert.12. What does a squash merge of a pull request do?
Correct answer: Combines the PR's commits into one commit on the target
The target gets a single tidy commit, and the branch's intermediate commits aren't in its history. Downsides: big PRs become one huge commit, and the branch looks unmerged to Git.
13. What does
git bisecthelp you find?Correct answer: The first commit that introduced a bug, by binary search
Mark a good and a bad commit, and Git checks out the middle for you to test. With 1,000 commits it takes about 10 steps, and
git bisect run <script>automates it.14. What is a Git hook?
Correct answer: A script Git runs on events like commit or push
Client-side hooks live in
.git/hooksand aren't committed, which is why tools like Husky install them from the repo. Server-side hooks (or CI) enforce rules for everyone.15. What is a
pre-commithook commonly used for?Correct answer: Running linters or formatters on staged files
Combined with lint-staged it checks only the files being committed, so it stays fast. It can be skipped with
--no-verify, so CI must still run the same checks.16. What does Conventional Commits standardize?
Correct answer: Message format like
feat(auth): add loginA type (
feat,fix,chore...), an optional scope andBREAKING CHANGEnotes make history machine-readable, so tools can generate changelogs and bump SemVer versions.17. What is trunk-based development?
Correct answer: Everyone integrates small changes into
mainoftenBranches live hours or a day or two, and unfinished features hide behind flags. It keeps conflicts small and is the basis of continuous integration.
18. How does Git Flow differ from GitHub Flow?
Correct answer: Git Flow adds
develop, release and hotfix branchesGit Flow suits versioned releases (apps, libraries); GitHub Flow suits continuous deployment. Many web teams find Git Flow's extra branches unnecessary overhead.
19. What do protected branches on GitHub or GitLab typically enforce?
Correct answer: Required reviews and passing checks before merge
They can also block force-pushes and deletions, and require linear history or signed commits. It's the server-side guarantee that hooks alone can't give.
20. What is a
CODEOWNERSfile?Correct answer: A map of paths to the people who must review changes there
When a pull request touches a path, its owners are requested as reviewers automatically, and branch protection can require their approval.
21. What does
git add -plet you do?Correct answer: Stage selected hunks of a file, not the whole file
Interactive staging lets you split unrelated changes in one file into separate commits, keeping history focused.
22. What is
ORIG_HEAD?Correct answer: Where
HEADwas before a merge, rebase or resetAfter a bad merge or rebase,
git reset --hard ORIG_HEADreturns to the previous state. The reflog offers the same and more history.23. What does the three-dot range
git log main...featureshow?Correct answer: Commits on either branch but not on both
It's the symmetric difference. With
--left-rightGit marks which side each commit is on. Forgit diff, three dots instead mean "changes since the merge base".24. What is the merge base of two branches?
Correct answer: Their best common ancestor commit
A three-way merge compares both tips against the merge base to see who changed what.
git merge-base main featureprints it.25. Annotated vs lightweight tags: what's the difference?
Correct answer: Annotated tags are objects with a message and tagger
A lightweight tag is just a ref to a commit. Use annotated (or signed) tags for releases: they record who tagged and when, and
git describeuses them by default.26. Why sign commits or tags with GPG or SSH keys?
Correct answer: To prove they were really made by the stated author
Anyone can set
user.emailto anything. Signatures let platforms show "Verified" and let protected branches require signed commits.27. What is a Git submodule?
Correct answer: Another repository pinned at a commit inside yours
The parent stores only the URL and commit hash. Clones need
--recurse-submodules, and updating means committing a new pinned hash, which is why many teams prefer packages or monorepos.28. What problem does
git worktreesolve?Correct answer: Checking out several branches in separate folders at once
You can review a PR or fix a hotfix in another directory without stashing your current work. All worktrees share one repository and object store.
29. What does a shallow clone (
git clone --depth 1) give you?Correct answer: Only the latest commit, which is fast for CI
CI rarely needs full history. But commands that need history (blame, merge-base for diffs,
git describe) may needgit fetch --unshallowor a deeper fetch.30. Why use Git LFS for large binary files?
Correct answer: Git keeps every version in full; LFS stores pointers
Binaries don't diff well, so each change adds the whole file to history forever and every clone downloads it. LFS stores the content on a separate server and fetches only needed versions.
31. What does
git log -S "apiKey"find?Correct answer: Commits that added or removed that string
The "pickaxe" search finds when a piece of code appeared or disappeared, even if it's gone now. For messages use
--grep, for current filesgit grep.32. How do you keep your fork in sync with the original repository?
Correct answer: Add it as
upstream, fetch, and merge or rebase from itgit remote add upstream <url>, thengit fetch upstreamandgit rebase upstream/main. Platforms also offer a "Sync fork" button for the default branch.33. What does
git fetch --prunedo?Correct answer: Deletes remote-tracking branches gone from the server
Without pruning,
origin/old-featurestays ingit branch -aforever. Setfetch.prune = trueto make it the default.34. What does
pull.ff = onlyin Git config do?Correct answer: Pull succeeds only if it can fast-forward
If your branch has diverged, pull stops instead of creating a surprise merge, and you decide whether to rebase or merge.
35. What does
git rebase --onto main old-base featuredo?Correct answer: Moves commits after
old-baseonfeatureontomainIt's for branches started from another feature branch: when the parent is merged or rewritten,
--ontotransplants only your own commits to the new base.36. What does
.git-blame-ignore-revshelp with?Correct answer: Hiding mass reformatting commits from
git blameAfter running Prettier on the whole codebase, every line blames that commit. Listing it in the file (with
blame.ignoreRevsFile) makes blame skip to the real authors; GitHub respects it too.37. What does
git stash -uadd compared with plaingit stash?Correct answer: It also stashes untracked files
Plain stash leaves new files in place, which can be surprising when you switch branches.
-aalso includes ignored files.38. How do you create a branch from a stash?
Correct answer:
git stash branch new-branchIt checks out the commit the stash was made on, creates the branch and applies the stash there, avoiding conflicts when the original branch has moved on.
39. What does
git rereredo?Correct answer: Remembers how you resolved conflicts and reuses it
"Reuse recorded resolution" helps when you rebase or re-merge the same branch repeatedly and hit the same conflict each time.
40. Why can a rebase with many commits be more painful than a merge?
Correct answer: Conflicts may need resolving once per replayed commit
Merge resolves differences once at the end; rebase replays commits one by one. Squashing the branch first or enabling rerere reduces the pain.
41. What does
git describeoutput, likev1.4.0-12-g3f2a9c1?Correct answer: The nearest tag, commits since it, and the short hash
Builds often embed it as a version: here 12 commits after
v1.4.0, at commit3f2a9c1(thegstands for git).42. What does
git shortlog -snshow?Correct answer: Commit counts per author, sorted by count
-ssummarizes counts and-nsorts numerically. It's handy for release notes and contributor lists.43. What happens to your commits when you squash-merge a PR and keep working on the same branch?
Correct answer: Git sees them as unmerged and they may conflict later
The squash commit has different content history, so the original commits aren't ancestors of
main. Start a new branch frommainafter a squash merge.44. What is
git cherry-pick -xuseful for?Correct answer: Noting "cherry picked from commit ..." in the message
On release branches the note links the backport to the original fix, which helps audits.
-n(--no-commit) is the option that applies changes without committing.45. How do you see which branches contain a given commit?
Correct answer:
git branch --contains <hash>Useful to check whether a fix reached a release branch. Add
-rfor remote branches, or usegit tag --containsfor releases.46. Why might renaming
File.jstofile.jscause trouble on macOS or Windows?Correct answer: Their default filesystems are case-insensitive
The OS treats both names as one file, so Git may not notice the change, while Linux CI sees two different paths. Use
git mv File.js file.js.47. What is
core.fileModeabout?Correct answer: Whether Git tracks the executable bit of files
On some filesystems permissions flip spuriously, making every file look modified. Setting it to
falsetells Git to ignore mode changes.48. What does
git range-diffcompare?Correct answer: Two versions of a commit series, before and after rebase
When a PR is force-pushed after review, range-diff shows what changed between the old and new commit series, not just the final diff.
49. What does
git commit --fixup=<hash>prepare?Correct answer: A commit that autosquash will fold into
<hash>It creates a commit titled
fixup! <original subject>. Latergit rebase -i --autosquashmoves and squashes it into the target commit.50. Why do many teams require linear history on
main?Correct answer: It's easier to read, bisect and revert
Each commit on
mainis a complete change you can test or revert on its own. Squash or rebase merges achieve this; protected branches can enforce it.51. What does
git log --graph --oneline --allhelp you see?Correct answer: How all branches diverge and merge over time
The ASCII graph shows parents and branch tips, which helps before a tricky merge or rebase. GUI tools draw the same graph.
52. You committed to
mainby mistake instead of a feature branch (not pushed). How do you fix it?Correct answer: Create the branch at HEAD, then reset
mainbackgit branch feature, thengit reset --hard origin/main(orHEAD~1), thengit switch feature. Since nothing was pushed, rewriting localmainis safe.53. What does
git clean -fdxremove?Correct answer: Untracked files and directories, including ignored ones
-dincludes directories and-xincludes ignored files such asnode_modulesand.env. It's a full reset of untracked content, so preview with-nfirst.54. Why is a long-lived feature branch risky?
Correct answer: It drifts from
main, so merging gets harderThe longer the divergence, the bigger the conflicts and the later integration bugs surface. Merge small pieces often, using feature flags for unfinished work.
55. What does
git diff --statshow?Correct answer: Changed files with added and removed line counts
It's a quick overview of a change's scope before you read the full diff.
--shortstatprints just the totals.56. What does
git restore --source=HEAD~2 file.jsdo?Correct answer: Puts the file's version from two commits ago on disk
Only the file changes; history and the branch stay. Commit the result if you want to keep the old version.
57. What is a release branch used for in Git Flow?
Correct answer: Stabilizing a version while
developmoves onOnly fixes go into the release branch; when done it's merged into
main(and tagged) and back intodevelop.58. How should a hotfix for production be handled with release branches?
Correct answer: Branch from the release tag, then merge the fix back
Branching from the deployed tag keeps unrelated work out of the hotfix. Merging or cherry-picking it back prevents the bug from returning in the next release.
59. What does
git grep "TODO"search?Correct answer: Tracked files in the working tree
It's fast and skips untracked and ignored files like
node_modules. You can also search another revision:git grep TODO v1.0.60. What does sparse checkout let you do in a big monorepo?
Correct answer: Check out only some directories of the repository
git sparse-checkout set apps/webkeeps the working tree small. Combined with a partial clone (--filter=blob:none) it also avoids downloading unneeded files.61. What does
git reset --mergeorgit merge --abortprotect thatreset --harddoesn't?Correct answer: Local changes that weren't part of the merge
They undo the merge result but keep unrelated uncommitted edits where possible.
--hardwould throw all uncommitted changes away.62. Why are generated files (build output, minified bundles) usually ignored?
Correct answer: They can be rebuilt, bloat history and cause noisy conflicts
Commit the source and build in CI instead. Exceptions exist, like a
distfolder in a GitHub Action that runs without a build step.63. What happens with
git commit --amendon a commit that's already pushed?Correct answer: You'll need a force-push, rewriting shared history
Amend creates a new commit, so the remote branch and your branch diverge. On your own PR branch that's acceptable with
--force-with-lease; onmainit isn't.64. What is the safest way to bring the latest
maininto a branch that others also push to?Correct answer: Merge
maininto it instead of rebasingMerge doesn't rewrite existing commits, so collaborators can keep pulling normally. Rebase is great for private branches, not shared ones.
65. What does
git log --first-parent mainshow?Correct answer: Only the commits made or merged directly on
mainIt follows only the first parent of merges, giving a clean list of merged PRs instead of every commit inside each branch.
66. What does
git switch -do?Correct answer: Switches back to the previously checked-out branch
Like
cd -in a shell,-means "the previous branch", handy for hopping between two branches.67. Where should you resolve a
package.jsonversion conflict between two feature branches?Correct answer: In the branch merged later, after updating it from
mainThe second branch to land is responsible for integrating with what's already on
main: update, resolve, re-run tests, then merge.68. What does
git revert HEAD~3..HEADdo?Correct answer: Reverts the last three commits, one revert each
Reverts are applied newest first. Add
--no-committo combine them into a single revert commit.69. How can you edit an older commit's content (not just its message) before pushing?
Correct answer: Mark it
editinrebase -i, amend, then--continueRebase stops at that commit; change files,
git commit --amend, andgit rebase --continuereplays the rest on top. Alternatively, make a--fixupcommit and autosquash.70. What is the risk of
git add .before every commit?Correct answer: Committing unrelated or secret files by accident
Review
git statusandgit diff --stagedbefore committing, and keep.gitignoreup to date.git add -pmakes you look at each change.71. What does
git log --since="2 weeks ago" -- src/apishow?Correct answer: Commits from the last two weeks that touched
src/apiThe
--separates revisions from paths. Combining time, author and path filters narrows history quickly.72. What is
git push --atomicfor?Correct answer: Updating several refs on the server all or nothing
When pushing a branch and a tag together,
--atomicensures you don't end up with the tag pushed but the branch rejected.73. Why do monorepos often use
CODEOWNERSand path-based CI?Correct answer: So teams review and test only the parts they own
One repository with many apps needs routing: owners review their paths, and CI runs jobs only for changed packages to stay fast.
74. What is the downside of rebase-and-merge on a hosting platform?
Correct answer: Commits get new hashes, unlike the branch
The target gets the PR's individual commits, rebased. Every commit should then build and pass tests on its own, or bisect will hit broken states.
75. What does
git merge --squash featuredo locally?Correct answer: Stages all of
feature's changes without committingYou then commit once with your own message. No merge commit is created and
featureisn't recorded as merged, the same as a squash merge on a hosting platform.