PrepStack › DevOps & Cloud › Git
Git interview cheat sheet
Objects & refs, merge vs rebase, undoing mistakes, workflows
Git questions show up in almost every engineering interview, from "what does git pull do" to "you force-pushed over a teammate's work, now what?". Interviewers want a mental model: Git is a graph of immutable commits plus movable pointers (refs). If you understand that, merge, rebase, reset and reflog all make sense. Read the 15-minute revision, then study the undo table near the end, since scenario questions are very common.
15-minute revision
- Git is a distributed version control tool (2005, Linus Torvalds). GitHub is a hosting service around Git that adds pull requests, issues, Actions and permissions.
- Three areas: working tree (your files) →
git add→ index / staging area →git commit→ repository (.git). - Git stores snapshots, not diffs: a commit points to a tree (directory), trees point to blobs (file content) and other trees. Objects are named by a hash of their content.
- Object id = SHA-1 of
"<type> <size>\0" + content. SHA-256 repos exist (git init --object-format=sha256); Git 3.0 plans SHA-256 as the default for new repos. - A branch is a movable pointer to a commit (a 41-byte file). HEAD usually points to a branch; detached HEAD means it points straight at a commit.
HEAD~2= grandparent along first parents.HEAD^2= the second parent of a merge commit.- Fast-forward just moves the pointer. A 3-way merge uses the merge base and makes a merge commit.
--squashstages all changes as one new commit with no merge link. - Rebase replays your commits on a new base, creating new commits with new ids. Golden rule: never rebase commits that others already have.
reset --softmoves the branch only;--mixed(default) also resets the index;--hardalso resets the working tree.revertadds a new undo commit and is safe for shared history.git restore= file contents,git switch= branches. Both split the old overloadedgit checkout(Git 2.23).- Reflog records where HEAD and each branch pointed. Lost a commit after reset or rebase?
git reflog, thengit reset --hard HEAD@{n}or make a branch there. git pull=fetch+merge(orrebasewith--rebase/pull.rebase=true). Use--force-with-lease, never plain--force, on shared branches.- Lightweight tag = just a name for a commit. Annotated tag = a real object with tagger, date, message and optional signature. Use annotated tags for releases.
git bisectbinary-searches history for the commit that broke something: ~log2(N) tests.git bisect run <script>automates it.- Strategies: Git Flow (develop + release branches), GitHub Flow (main + short feature branches + PRs), trunk-based (tiny branches, feature flags, deploy main).
- Pushed a secret? Revoke and rotate it first. Rewriting history (
git filter-repo) comes second, because clones and forks may already have it.
Foundations
Git vs GitHub & distributed VCS
Git is the version control tool on your machine. GitHub, GitLab and Bitbucket are services that host Git repos and add collaboration features.
- Git is a free, open-source distributed version control system. Every clone has the full history, so commits, branches, log and diff work offline.
- Centralized systems (SVN, Perforce) keep history on one server, so most actions need the network. With Git, the server is a copy that the team agrees to treat as the source of truth.
- GitHub (owned by Microsoft since 2018) adds pull requests, code review, issues, Actions CI/CD, branch protection, forks, and security scanning. None of these are part of Git itself.
- A remote (usually
origin) is just a named URL of another copy of the repository. Git syncs objects and refs with it usingfetchandpush. - Git is a content-addressable store: everything is named by a hash of its content, which gives integrity checks for free.
Interview questions
- What is the difference between Git and GitHub?
- Why is Git called distributed, and what are the benefits?
Working tree, index & repository (+ diff)
Changes move from the working tree, to the index (staging area) with git add, to the repository with git commit. git diff compares these areas.
- Working tree: the files you edit on disk. Index (staging area,
.git/index): the exact snapshot the next commit will contain. Repository: the commit objects in.git/objects. - Staging lets you build focused commits:
git add -pstages single hunks, so one file can be split across two commits. - File states: untracked →
add→ staged →commit→ unmodified → edit → modified. git statuscompares HEAD vs index ("Changes to be committed") and index vs working tree ("Changes not staged").git diff= working tree vs index.git diff --staged(same as--cached) = index vs HEAD.git diff HEAD= working tree vs HEAD.git diff a..bcompares the two tips.git diff a...bcompares the merge base of a and b with b, which shows "what my branch changed", like a PR view.
Interview questions
- What is the staging area (index) and why does Git have it?
- Difference between
git diff,git diff --stagedandgit diff HEAD? - Difference between
git diff a..bandgit diff a...b?
Object model: blob, tree, commit, tag
Git is a content-addressable key-value store of four immutable object types, each named by the hash of its content.
- Blob: file contents only. No name and no permissions. Two identical files anywhere in history share one blob.
- Tree: a directory listing. Each entry is mode + name + id of a blob or sub-tree.
- Commit: a root tree id, zero or more parent ids, author, committer, timestamps and message. Changing any of these gives a new id, so history cannot be edited in place. It can only be replaced.
- Tag (annotated): points to an object (usually a commit) and adds tagger, date, message and optional signature.
- Object id = hash of
"<type> <size>\0" + content. Loose objects are zlib-compressed in.git/objects/ab/cdef....git gcpacks them into packfiles with delta compression. - SHA-1 → SHA-256: SHA-1 collisions became practical (SHAttered, 2017). Git now uses hardened SHA-1 that detects known collision attacks. SHA-256 repos are supported (
--object-format=sha256), and Git 3.0 plans to make SHA-256 the default for new repos. Hosting support is still catching up.
Interview questions
- Does Git store diffs or snapshots?
- What are the four Git object types?
- Why does amending or rebasing change the commit hash?
- Is SHA-1 in Git a security problem? What is the SHA-256 transition?
Refs, HEAD, branches & detached HEAD
A branch is a named pointer to a commit. HEAD says which branch (or commit) you are on. Committing moves the current branch forward.
- Refs live in
.git/refs/heads/*(local branches),refs/remotes/origin/*(remote-tracking) andrefs/tags/*. Many are packed into.git/packed-refs. Git 3.0 plans the reftable backend as default. - HEAD is normally symbolic:
ref: refs/heads/main. When you commit, Git moves the branch HEAD points to. - Creating a branch is O(1): it writes one pointer. Nothing is copied. That is why Git branching is cheap compared to SVN.
- Detached HEAD: HEAD holds a commit id directly (after
git switch --detach <id>, checking out a tag, or during rebase/bisect). New commits there belong to no branch. - If you leave a detached HEAD, those commits become unreachable and are later garbage-collected. Save them with
git switch -c new-branchfirst. - Relative refs:
HEAD~3(3 first-parents back),HEAD^2(second parent of a merge),main@{1}(previous value of main from reflog),@{u}(upstream branch).
Interview questions
- What is a branch in Git?
- What is HEAD, and what is a detached HEAD?
- Difference between
HEAD~2andHEAD^2?
Commits, amend & .gitignore
Make small, focused commits with clear messages. --amend replaces the last commit. .gitignore stops untracked files from being added.
- Good commit: one logical change, builds and passes tests, subject ≤ ~50 chars in imperative mood ("Add retry to payment client"), blank line, body that explains why.
git commit --amendmakes a new commit that replaces the last one (fix the message, add a forgotten file). Use--no-editto keep the message. Only amend commits you have not pushed, or be ready to force-push your own branch..gitignorepatterns:*.log,build/(directory),/config.local(root only),**/tmp, and!keep.logto re-include. Later rules win.- Ignore rules only affect untracked files. If a file is already tracked, run
git rm --cached filethen commit, and the ignore rule applies from then on. - Other ignore sources:
.git/info/exclude(local only, not shared) and a global file viacore.excludesFile(for editor and OS junk like.DS_Store). - Debug with
git check-ignore -v path. It prints which file and line ignored it.
Interview questions
- I added a file to
.gitignorebut Git still tracks it. Why? - What does
git commit --amenddo, and when is it dangerous? - What makes a good commit message?
Branching & integrating
Merging: fast-forward, 3-way & squash
If your branch has not moved, Git just slides the pointer forward. If both sides moved, it does a 3-way merge from the common ancestor and records a merge commit.
- Fast-forward: the target is an ancestor of the source, so the branch pointer just moves. No new commit, and history stays linear.
- 3-way merge: both branches have new commits. Git finds the merge base (best common ancestor), combines both sets of changes, and creates a merge commit with two parents.
--no-ffforces a merge commit even when a fast-forward is possible, which keeps a visible "feature landed here" bubble.--ff-onlyrefuses anything but a fast-forward.--squashapplies all changes from the branch to the index as one new commit with a single parent. Git does not record the merge, so merging that branch again later can cause conflicts.- The default merge strategy is ort (since Git 2.34; it replaced
recursive). Options like-X ours/-X theirschoose a side only for conflicting hunks. - GitHub's PR buttons map to these: Create a merge commit, Squash and merge, Rebase and merge.
Interview questions
- What is a fast-forward merge?
- How does a three-way merge work?
- Squash merge vs regular merge vs rebase merge: which would you pick?
Merge conflicts & resolution
A conflict happens when both sides changed the same lines (or one edited a file the other deleted). Git stops, marks the file, and waits for you to decide.
- Conflict markers:
<<<<<<<ours,=======,>>>>>>>theirs. Withmerge.conflictStyle=zdiff3you also see the base version between|||||||and=======, which makes the intent clear. - Flow:
git status(lists unmerged paths) → edit files or use a merge tool →git addeach file →git commit(merge) orgit rebase --continue. - Bail out anytime:
git merge --abort,git rebase --abort,git cherry-pick --abort. - Take a whole side for one file:
git checkout --ours fileor--theirs file, thengit add. During a rebase, ours and theirs are swapped: ours = the branch you are rebasing onto, theirs = your commit being replayed. git rerere("reuse recorded resolution",rerere.enabled=true) remembers how you fixed a conflict and reapplies it next time. Useful for long-lived branches and repeated rebases.- Prevent conflicts: small PRs, merge or rebase from main often, avoid mass reformatting, and agree on formatters.
Interview questions
- How do you resolve a merge conflict?
- In a rebase conflict, what do "ours" and "theirs" mean?
- What is
git rerere?
Rebase, interactive rebase & autosquash
Rebase replays your commits on top of another base, creating new commits for a linear history. Interactive rebase lets you squash, reword, reorder or drop commits before sharing.
git rebase main(while on feature): find the merge base, save your commits as patches, move to main's tip, and re-apply them one by one. Each gets a new id.- Golden rule: never rebase commits that exist outside your repo and that others may have built on (shared
main, a teammate's branch). Rebasing your own feature branch before merging is fine. git rebase -i HEAD~5opens a todo list:pick,reword(edit message),edit(stop to amend),squash(meld into previous and combine messages),fixup(meld and drop this message),drop, plus reordering lines.- Autosquash:
git commit --fixup=<sha>createsfixup! <subject>. Latergit rebase -i --autosquash mainmoves it under its target and marks itfixupautomatically. Setrebase.autoSquash=trueto make it the default. git rebase --onto new-base old-base branchmoves only part of a branch, for example when a feature was started from the wrong branch.--update-refs(Git 2.38+) also moves other branches that point into the rebased range, which helps with stacked PRs.
Interview questions
- What is the difference between merge and rebase?
- What is the golden rule of rebasing and why?
- Squash vs fixup in interactive rebase?
- Your feature branch was created from
developby mistake but should be based onmain. How do you fix it?
Cherry-pick
git cherry-pick <sha> copies the change from one commit onto your current branch as a new commit.
- Typical uses: backport a hotfix to a release branch, rescue one commit from an abandoned branch, or move a commit made on the wrong branch.
- The new commit has the same diff and message but a different id (different parent).
-xappends "(cherry picked from commit ...)" to the message, which is good for traceability on release branches.- Ranges:
git cherry-pick A..Bpicks commits after A up to B (A excluded). UseA^..Bto include A. - Picking a merge commit needs
-m 1to choose which parent the diff is taken against. - Downsides: duplicate commits on two branches can cause confusing conflicts later. Prefer merging the fix into both branches when the history allows it.
Interview questions
- What is
git cherry-pickand when would you use it? - What are the risks of cherry-picking a lot?
Undoing & recovery
reset vs revert vs restore vs checkout/switch
reset moves the branch pointer (rewrites history), revert adds a new commit that undoes one (safe when shared), restore changes files, and switch changes branches.
git reset --soft <c>: move the branch to<c>. Index and working tree unchanged, so the undone commits' changes stay staged. Good for re-committing as one.git reset --mixed <c>(default): also reset the index. Changes stay in the working tree but are unstaged.git reset --hard <c>: also overwrite the working tree. Uncommitted changes are lost (committed ones are still recoverable via reflog).git revert <c>creates a new commit with the inverse change. History is kept, so it is the right tool for anything already pushed. For a merge commit usegit revert -m 1 <merge>.git restore <file>discards working-tree edits.git restore --staged <file>unstages.git restore --source=HEAD~2 <file>brings back an old version of the file.git checkoutused to do both jobs (switch branches and restore files). Since 2.23,switchandrestoresplit those jobs and make mistakes less likely.
Interview questions
- Difference between
git resetandgit revert? - Explain
--soft,--mixedand--hard. - Difference between
git checkout,git switchandgit restore? - How do you undo a merge that was already pushed to main?
Reflog & recovering lost commits
The reflog is a local log of every position HEAD and each branch has had. It is the safety net that makes almost any Git mistake recoverable.
- Every time HEAD or a branch moves (commit, reset, rebase, checkout, merge, amend), Git appends an entry to
.git/logs/. View it withgit reflogorgit reflog show feature. - Syntax:
HEAD@{2}(two moves ago),main@{1},main@{yesterday},@{-1}(previously checked-out branch). - Recover: find the entry before the mistake, then
git reset --hard HEAD@{n}, or safergit branch rescue <sha>. - Reflog is local only. It is never pushed, and a fresh clone has an empty reflog.
- Entries expire: by default 90 days for reachable entries (
gc.reflogExpire) and 30 days for unreachable ones (gc.reflogExpireUnreachable). After that,git gcmay prune the objects (aftergc.pruneExpire, 2 weeks by default). - No reflog entry (deleted repo's reflog, or a dropped stash)?
git fsck --lost-found/--unreachablelists dangling commits and blobs.
Interview questions
- What is the reflog and how is it different from
git log? - You ran
git reset --hardand lost commits. How do you get them back? - Can you recover a deleted branch?
Stash & worktrees: switching context
Stash parks uncommitted changes so you can switch branches. A worktree gives you a second checked-out branch in another folder, with no stashing at all.
git stash(=git stash push) saves tracked staged and unstaged changes and cleans the working tree.-uincludes untracked files,-aalso ignored ones.git stash popapplies and drops the entry.git stash applykeeps it in the list. If there is a conflict,popdoes not drop it.git stash push -m "msg" -- path/stashes only some paths.git stash list,show -p stash@{1},drop,clear.git stash branch new-branchcreates a branch at the commit where you stashed and applies the stash there. This avoids conflicts when main has moved.- Worktrees:
git worktree add ../app-hotfix -b hotfix mainchecks out another branch in a sibling folder that shares the same.gitobjects. Great for reviewing a PR or a hotfix while a long build runs. - The same branch cannot be checked out in two worktrees at once. Clean up with
git worktree removeandgit worktree prune.
Interview questions
- What is
git stashand what is the difference betweenpopandapply? - Does
git stashsave untracked files? - What is a Git worktree and when would you use it?
Undo scenarios cheat table
Most "I broke Git" questions come down to: was it pushed? If not, rewrite freely. If yes, add new commits (revert) or coordinate a force-push.
- First question to ask: is it pushed or shared? Local → reset, amend or rebase. Shared → revert, or tell the team before any force-push.
- Second question: is it committed? Committed work is almost always recoverable through the reflog. Uncommitted work wiped by
reset --hardorrestoreusually is not. - Before anything risky, create a backup pointer:
git branch backup-before-fix. It costs nothing. - For leaked secrets, the order is: revoke/rotate, then clean history, then force-push, and ask GitHub support to purge cached views if needed. History rewriting alone is never enough.
- Use
git filter-repo(recommended by Git docs) or BFG to remove files from all history.git filter-branchis slow and discouraged.
Interview questions
- You committed to
mainby mistake and have not pushed. How do you move the commit to a new branch? - You pushed a commit containing an AWS key. What do you do?
- A teammate force-pushed and your commits disappeared from the remote branch. How do you recover?
Remotes & team workflow
Remotes: fetch, pull, push
fetch downloads new commits and updates origin/*. pull is fetch plus merge or rebase. push uploads commits and moves the remote branch, but only by fast-forward unless forced.
git fetchis always safe. It updates remote-tracking refs (origin/main) and never touches your branches or files.--pruneremoves refs for deleted remote branches.git pull=fetch+ integrate into the current branch. Default is merge.pull --rebase(orpull.rebase=true) rebases your local commits on top.pull.ff=onlyrefuses to create merges.- Upstream (tracking) branch:
git push -u origin featuresets it, then plaingit push/git pullknow where to go.git statusshows ahead/behind. - Push is rejected (non-fast-forward) when the remote has commits you do not have. Fetch and integrate first. Do not force-push to solve it on shared branches.
--force-with-leaseonly overwrites if the remote is still where yourorigin/xsays. If someone pushed in between, it fails instead of deleting their work. Add--force-if-includes(2.30+) to protect against a background fetch updatingorigin/xbehind your back.- Forks:
origin= your fork,upstream= the original repo. Sync withgit fetch upstream && git rebase upstream/main.
Interview questions
- Difference between
git fetchandgit pull? - What is
--force-with-leaseand why is it safer than--force? - Why was my push rejected with "non-fast-forward"?
- Should
git pullmerge or rebase?
Branching strategies & PR workflow
Git Flow uses long-lived develop and release branches, GitHub Flow uses main plus short PR branches, and trunk-based development uses very short branches and feature flags with continuous deployment.
- Git Flow:
main(released),develop(integration),feature/*,release/*,hotfix/*. Fits versioned, scheduled releases (mobile apps, on-prem software). Heavy for web apps that deploy daily. - GitHub Flow:
mainis always deployable. Branch → commits → PR → review + CI → merge → deploy. Simple and the default for most SaaS teams. - Trunk-based development: everyone integrates into trunk at least daily. Branches live hours, not weeks. Unfinished work hides behind feature flags. Needs strong CI and is what DORA research ties to high performance.
- PR workflow: small focused PRs, a clear description (what, why, how tested), CI must pass, required reviewers via CODEOWNERS, branch protection or rulesets on main (no direct push, no force-push, status checks, signed commits).
- Good code review: check correctness, design, tests, security and naming. Be specific and kind, separate blocking from nit comments, and review within hours, since slow reviews kill flow.
- A merge queue tests each PR against the latest main plus PRs ahead of it, which avoids "green PR, red main" on busy repos.
Interview questions
- Compare Git Flow, GitHub Flow and trunk-based development.
- What makes a good pull request?
- How do you enforce quality on the main branch?
- How does trunk-based development handle unfinished features?
Debugging history & extending Git
bisect, blame & searching history
git bisect finds the commit that introduced a bug by binary search. git blame shows who last changed each line. git log -S finds when a string appeared or disappeared.
- Bisect:
git bisect start,git bisect bad(current),git bisect good v1.4.0. Git checks out the midpoint, you test and mark good/bad, and repeat. About log2(N) steps: 1000 commits ≈ 10 tests. - Automate with
git bisect run ./test.sh: exit 0 = good, 1–127 = bad, 125 = skip (cannot test this commit). Finish withgit bisect reset. git bisect skipfor commits that do not build.git bisect terms --term-old=fast --term-new=slowfor non-bug hunts like performance regressions.git blame fileshows commit, author and date per line.-wignores whitespace,-M/-Cfollow moved or copied lines,-L 40,60limits lines. List formatting commits in.git-blame-ignore-revsand setblame.ignoreRevsFile.- Search history:
git log -S "apiKey"(pickaxe: commits that add or remove that string),git log -G regex,git log -L :funcName:file.py(history of one function),git log --author,--since,-- path. git grepsearches tracked files fast, and can search any commit:git grep TODO v1.0.
Interview questions
- How would you find which commit introduced a bug among 500 commits?
- What does
git blamedo and what are its pitfalls? - How do you find the commit that removed a specific function call?
Submodules vs subtrees
A submodule is a pointer to a specific commit of another repo. A subtree copies the other repo's files into a folder of yours. Submodules are precise but awkward; subtrees are simple for users but harder to sync back.
- Submodule:
git submodule add <url> libs/xwrites.gitmodules(path + URL) and a special gitlink entry (mode 160000) in the tree that pins an exact commit. - Clone with
git clone --recurse-submodules, or afterwardsgit submodule update --init --recursive. Updating the pin: go into the submodule, check out a newer commit, then commit the new pointer in the parent repo. - Common pain: people forget
--recurse-submodules, end up in detached HEAD inside the submodule, or forget to push the submodule commit the parent points to. - Subtree (
git subtree add --prefix=libs/x <url> main --squash): the files become normal files in your repo. Cloning needs nothing special.git subtree pull/pushsyncs with upstream. - Alternatives that are often better: a package manager (npm, Maven, Go modules) with versioned releases, or a monorepo.
Interview questions
- Submodules vs subtrees: which would you choose?
- Why does
git statusshow a submodule as modified when you did not change anything?
Hooks & signing commits
Hooks are scripts Git runs at certain events (pre-commit, commit-msg, pre-push) to automate checks. Signing commits and tags proves who created them.
- Client hooks live in
.git/hooks/and are not versioned or shared. Teams share them viacore.hooksPath(a tracked folder) or tools like pre-commit, Husky + lint-staged, or Lefthook. - pre-commit: runs before the commit is created (lint, format, secret scan, tests on staged files). A non-zero exit aborts the commit. commit-msg: gets the message file path as
$1, which is used to enforce Conventional Commits. pre-push: slower checks before pushing. - Server-side hooks (
pre-receive,update,post-receive) run on the server. On GitHub you use branch rules, required checks and push protection instead. - Hooks are advisory:
git commit --no-verifyskips pre-commit and commit-msg. Always enforce the same rules again in CI. - Signing: Git records any name and email you configure, so authorship can be faked. Signing with GPG, SSH (Git 2.34+) or X.509 (gitsign/Sigstore) proves the key holder made the commit. GitHub shows a Verified badge, and rulesets can require signed commits.
- Sign with
git commit -S/git tag -s, or always withcommit.gpgsign=true. Verify withgit log --show-signatureorgit verify-commit.
Interview questions
- What are Git hooks? Give examples.
- Can you rely on hooks to enforce rules?
- Why sign commits, and how?
Scale: large files & monorepos
Large files (LFS) & monorepo performance
Git is built for text and full history on every clone. For big binaries use Git LFS. For huge repos use partial clone, sparse checkout and background maintenance.
- Every version of every file lives in history forever, and every clone downloads it. Large binaries (videos, models, PSDs) make clones slow and bloat the repo. GitHub warns above 50 MB and blocks files over 100 MB.
- Git LFS:
git lfs track "*.psd"writes a rule to.gitattributes. The repo stores a small pointer file (oid sha256 + size), while the real content goes to an LFS server and is downloaded on checkout. Convert existing history withgit lfs migrate import --include="*.psd". - Shallow clone
--depth 1: only recent commits. Good for CI builds, but limits log, blame and merge-base. - Partial clone
--filter=blob:none: all commits and trees, but blobs are fetched on demand. Keeps full history usable.--filter=tree:0is even lighter (good for CI that only needs one checkout). - Sparse checkout
git sparse-checkout set --cone services/api libs/common: only those folders are in the working tree. Combine with partial clone for big monorepos. - Performance helpers:
git maintenance start(background prefetch, commit-graph, repack),core.fsmonitor=true(file-system watcher speeds up status), the commit-graph file, andscalar(bundles these settings for large repos).
Interview questions
- How do you handle large binary files in Git?
- Shallow clone vs partial clone vs sparse checkout?
- Your monorepo's
git statustakes 10 seconds. What can you do?