Back to interview questions

100+ Git Interview Questions and Answers

100+ Git Interview Questions and Answers

Explore 120 Git interview questions and answers covering staging, branches, merging, rebasing, recovery, remotes, worktrees and release integrity.

Explore 120 Git interview questions and answers covering staging, branches, merging, rebasing, recovery, remotes, worktrees and release integrity.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Git interviews should show whether a developer can explain what will change before running a command and recover calmly when the result differs from expectations. Hiring teams need evidence of repository-state reasoning, collaboration and review discipline, not only a memorized list of commands. The distinction between an edit, a staged snapshot, a commit and a shared reference is central to that judgment.

These 100+ Git Interview Questions and Answers provide 120 questions across beginner, intermediate and experienced levels. They progress from everyday recording and branching to integration, recovery, object storage, large repositories, CI and release integrity. Select scenarios that match the candidateโ€™s responsibility for individual changes, shared branches or repository operations.

How can recruiters distinguish confident Git command recall from safe, practical repository judgment?

Present a concrete state: one file has staged and unstaged edits, a remote branch advanced during a rewrite or a useful commit was created in detached HEAD. Ask the candidate to inspect the evidence, state the desired outcome and explain the least disruptive sequence that achieves it. Strong answers distinguish known facts from stale references and verify the resulting content instead of treating a successful command as sufficient.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation and unauthorized assistance during remote interviews. Pair those signals with a disposable-repository exercise and follow-up questions about the candidateโ€™s choices. Review the evidence in context rather than treating a single signal as conclusive proof of misconduct.

Git Interview Questions

Choose a balanced interview from the full bank below. The answer section uses the same question wording and numbering, so a command definition can lead naturally into a collaboration or recovery scenario.

Git Interview Questions for Beginners

Assess the working tree, index, commits, branches, remotes and everyday change-recording workflow.

  1. What problem does Git solve?

  2. How do Git and hosting services such as GitHub differ?

  3. What are the working tree, index and repository history?

  4. What is a commit?

  5. What does git init do?

  6. What does git clone do?

  7. What does git status tell you?

  8. What does git add actually stage?

  9. How do git diff and git diff --cached differ?

  10. What does git commit record by default?

  11. What makes a useful commit message?

  12. How do you inspect commit history?

  13. What does git show display?

  14. What is a branch in Git?

  15. What does HEAD represent?

  16. How do you create and switch branches?

  17. What does detached HEAD mean?

  18. What is a merge?

  19. What is a fast-forward merge?

  20. What causes a merge conflict?

  21. What is a remote?

  22. What does git fetch do?

  23. How does git pull differ from git fetch?

  24. What does git push do?

  25. What is a remote-tracking branch?

  26. What does an upstream branch configure?

  27. What do ahead and behind counts mean?

  28. How does .gitignore work?

  29. How do you stop tracking a file while keeping a local copy?

  30. How do you unstage a change without discarding the working edit?

  31. How do you discard an unstaged edit deliberately?

  32. How do reset, restore and revert differ at a high level?

  33. What is a tag?

  34. What is git stash useful for?

  35. How do stash apply and stash pop differ?

  36. What does git rm do?

  37. How does Git recognize a renamed file?

  38. What are author and committer identities?

  39. How do configuration scopes affect Git behavior?

  40. What should you inspect before changing repository history?

Git Interview Questions for Intermediate

Explore selective staging, integration, rewriting, diagnostics, recovery and common collaboration tools.

  1. How can you stage only part of a file?

  2. What does amending a commit change?

  3. How do soft, mixed and hard reset modes differ?

  4. When is revert preferable to rewriting history?

  5. How do merge and rebase differ?

  6. How do you resolve a rebase conflict?

  7. What can interactive rebase do?

  8. How do fixup commits and autosquash work together?

  9. How do you split one local commit into several coherent commits?

  10. What does cherry-pick do?

  11. Why can ours and theirs be confusing during a rebase?

  12. How can you inspect the three stages of an unresolved merge?

  13. What does git merge --abort attempt to do?

  14. How does git reflog help recover a moved branch or detached commit?

  15. What does ORIG_HEAD represent?

  16. How do you compare a feature branch with its base?

  17. What is a merge base?

  18. How do you respond to a non-fast-forward push rejection?

  19. What protection does force-with-lease provide?

  20. How does a remote default branch differ from origin/HEAD and the current local branch?

  21. How do you delete a local branch safely?

  22. How does pruning remote-tracking references differ from deleting remote branches?

  23. How are tags transferred to a remote?

  24. What are signed commits and tags useful for?

  25. How does git bisect locate a regression?

  26. How can git blame be used responsibly?

  27. When is log -S different from log -G?

  28. How do pathspecs and the double-dash separator prevent command ambiguity?

  29. How do line-ending policies affect collaboration?

  30. What can .gitattributes control beyond line endings?

  31. What are Git hooks, and where should enforcement live?

  32. How do patches differ from bundles?

  33. How do git apply and git am differ?

  34. What does a squash merge preserve and omit?

  35. What is a worktree useful for?

  36. How do submodules record dependencies?

  37. How do shallow clones affect history operations?

  38. How do sparse checkout and partial clone differ?

  39. Why should git clean be used cautiously?

  40. How do you validate that a rewritten patch series still contains the intended changes?

Git Interview Questions for Experienced

Assess object mechanics, concurrency, repository maintenance, cross-platform behavior and release evidence.

  1. How do blobs, trees, commits and tag objects relate?

  2. How do symbolic references differ from direct references?

  3. Why does changing a commit's parent change its identifier even when its files are unchanged?

  4. Why are commit timestamps insufficient for determining ancestry?

  5. What does it mean for an object to be reachable?

  6. How do garbage collection and reflog expiry affect recovery?

  7. What can git fsck establish?

  8. How do packfiles and delta compression affect Git's snapshot model?

  9. What are replacement references, and why can they complicate investigation?

  10. What should happen after a secret is committed?

  11. What does Git LFS change about large-file storage?

  12. How would you investigate an unexpectedly large repository?

  13. Which worktree state is shared, and why does it matter?

  14. Why does reverting a merge require choosing a mainline parent?

  15. Why may merging a branch again after reverting its merge not restore the old changes?

  16. How can criss-cross history affect merge-base selection?

  17. What is rerere, and what precautions does it need?

  18. How should binary-file conflicts be handled?

  19. How does the ours merge strategy differ from the ours strategy option?

  20. Why can large rename-heavy merges be expensive or confusing?

  21. How do you make automated bisect results trustworthy?

  22. How do you resolve a submodule commit conflict?

  23. How should stale worktree metadata be cleaned up?

  24. How do refspecs control fetch and push scope?

  25. What does an atomic push guarantee?

  26. How do server-side receive hooks differ from local hooks?

  27. Why is commit identity different from push authentication?

  28. What is the purpose of safe.directory checks?

  29. What should you consider before running code from an unfamiliar repository?

  30. Why should CI report the exact commit or tree it tested?

  31. How can a merge queue reduce integration failures?

  32. How do you connect a release tag to a deployed artifact reliably?

  33. What trade-offs matter when choosing a monorepo or multiple repositories?

  34. What does a sparse index optimize?

  35. Why should scripts avoid assuming every object ID has exactly 40 characters?

  36. What problems can case-insensitive filesystems create for Git?

  37. How does Git represent executable bits and symbolic links?

  38. What should you know before using git archive as a source package?

  39. How should parallel automation avoid corrupting a shared checkout's workflow?

  40. How would you respond to an accidental destructive Git operation?

Git Interview Questions and Answers

The examples distinguish read-only inspection from changes to files, references and shared history. Commands that alter state are intended for disposable demonstration repositories or a deliberately reviewed workflow. Inspect the repository and preserve valuable work before applying any recovery or rewrite technique.

Git Interview Questions and Answers for Beginners

These answers establish the state model needed to explain what a command actually reads or changes.

1. What problem does Git solve?

Git records versions of a project and their relationships so people can inspect changes, develop independently and combine work. It provides a local repository with history rather than relying on a central server for every operation. It does not automatically decide whether a change is correct or replace backups of data that was never recorded.

I would use it to make a change reviewable and recoverable through meaningful commits, then share selected history with collaborators. A clean Git status only describes the relationship among tracked project states; it does not prove tests passed or that an external database matches the code. Good use combines version control with review and validation.

2. How do Git and hosting services such as GitHub differ?

Git is the version-control system that stores objects, references and history and performs operations such as commit, merge and fetch. A hosting service adds facilities such as remote repositories, pull requests, permissions and CI integration. Those service features are not all part of Git's core protocol or local repository.

I can commit and inspect history without an internet connection, then push when access is available. A pull request is a collaboration object on the hosting platform, not a special kind of Git commit. When an operation fails, I would distinguish local Git behavior from network authentication, repository permissions and platform branch policies.

3. What are the working tree, index and repository history?

The working tree contains checked-out files, the index records the proposed snapshot for the next commit, and repository history contains recorded commits and their referenced objects. These states can differ at the same time. Staging does not continuously track subsequent edits to a file.

If I edit a file, stage it and edit it again, the index contains the earlier staged version while the working tree contains the later one. I would inspect both unstaged and staged diffs before committing. This model explains why a commit can succeed without including every visible edit in the editor.

# Disposable demo repository: notes.txt is tracked and initially contains "base".
printf 'staged line\n' >> notes.txt
git add -- notes.txt
printf 'unstaged line\n' >> notes.txt
git diff --cached -- notes.txt
git diff -- notes.txt
# The first diff shows the staged line; the second shows the later edit.
# Disposable demo repository: notes.txt is tracked and initially contains "base".
printf 'staged line\n' >> notes.txt
git add -- notes.txt
printf 'unstaged line\n' >> notes.txt
git diff --cached -- notes.txt
git diff -- notes.txt
# The first diff shows the staged line; the second shows the later edit.
# Disposable demo repository: notes.txt is tracked and initially contains "base".
printf 'staged line\n' >> notes.txt
git add -- notes.txt
printf 'unstaged line\n' >> notes.txt
git diff --cached -- notes.txt
git diff -- notes.txt
# The first diff shows the staged line; the second shows the later edit.

State

What it represents

How to inspect

Working tree

Current checked-out files

git diff

Index

Proposed next snapshot

git diff --cached

HEAD tree

Current recorded snapshot

git show HEAD:path

4. What is a commit?

A commit records a tree snapshot, parent relationship or relationships, author and committer information and a message. Its object identifier depends on its contents, including metadata and parents. It is not merely a mutable label for a group of changed lines.

Two commits can contain the same file snapshot but have different identifiers because their parents or metadata differ. I would use the message to explain the reason for a coherent change, while the tree establishes what was recorded. Creating a commit is local; collaborators do not receive it until history is transferred through an appropriate sharing operation.

5. What does git init do?

git init creates the repository metadata needed to begin versioning a directory, or initializes a bare repository when requested. It does not automatically stage or commit existing files. The initial branch name depends on options and configuration, so scripts should avoid assuming one universal default.

For a new project, I would initialize the intended directory, inspect status and add a suitable ignore policy before staging files. Running init in the wrong directory can create a confusing repository boundary. The command is a setup step; meaningful history still requires deliberate commits.

6. What does git clone do?

git clone creates a local repository from another repository and usually checks out an initial working tree. It sets up remote configuration and remote-tracking references according to the clone options. Shallow, partial and single-branch clones can intentionally omit information available in a full clone.

I would inspect the configured remote and current branch after cloning, especially when automation uses special options. A clone contains Git-managed history and objects within its scope, not every hosting-service setting, issue or secret. It also does not automatically install the project's dependencies or prove that its code is safe to execute.

7. What does git status tell you?

git status summarizes the working tree and index relative to the current commit and can report branch tracking information. It distinguishes staged, unstaged and untracked changes. Ahead or behind information reflects the locally known remote-tracking state, which may be stale until a fetch.

Before changing branches or committing, I use status to understand what work exists and whether an operation is already in progress. A clean status does not mean ignored files are absent or that the repository matches the live remote at that instant. For scripts, a stable porcelain format is preferable to parsing human-oriented prose.

8. What does git add actually stage?

git add updates the index with the selected path contents as they exist when the command runs. It can stage modifications, additions and removals according to the command's pathspec and options. It does not create a commit or automatically include future edits.

I would add specific paths or selected patches when several unrelated changes are present, then inspect the staged diff. Broad staging can accidentally include generated output or credentials if the ignore policy is incomplete. The correct question is which snapshot will be committed, not simply whether a filename has been added at least once.

9. How do git diff and git diff --cached differ?

By default, git diff compares the working tree with the index, showing unstaged changes. git diff --cached compares the index with HEAD, showing what is staged for the next commit. Other arguments change the compared endpoints, so the command's exact form matters.

If the same file has staged and unstaged edits, I would inspect both views before committing. Looking only at the ordinary diff can miss an accidentally staged change, while looking only at the cached diff can miss a later edit that will remain uncommitted. Explicit comparison points make review more reliable than treating every diff command as interchangeable.

10. What does git commit record by default?

A normal git commit records the current index as a new commit, subject to checks and hooks. It does not automatically record every modified or untracked working-tree file. Options such as -a alter staging behavior for tracked files but still do not mean every new file is included.

I would review the staged snapshot and run relevant checks before creating the commit. If a file was changed after staging, that later edit can remain in the working tree afterward. A useful commit is a coherent unit that a reviewer can understand and, when appropriate, revert independently.

11. What makes a useful commit message?

A useful message states the concrete change and explains the reason or constraint when it is not obvious from the diff. It should help a future reader understand the decision without needing the original conversation. The repository's conventions can guide structure, but formatting alone does not make a message informative.

For a bug fix, I would describe the trigger and corrected behavior rather than write only fix bug. Avoid claiming tests passed unless they did, and include important limitations where the team's workflow expects them. A message cannot compensate for a commit that mixes several unrelated changes and is difficult to review.

12. How do you inspect commit history?

git log shows commits reachable from selected references, with options to control format, graph display, paths and filtering. The default view is not necessarily every object ever created in the repository. History interpretation depends on the selected references and range.

I would use a concise graph for branch relationships and a patch view when investigating the change itself. A path filter can help find relevant work, but renames and merges can affect what appears. If a commit seems missing, check reachability and filters before concluding it was deleted permanently.

13. What does git show display?

git show displays an object's information, commonly a commit's metadata and patch. It can also inspect a file from a particular revision using revision-and-path syntax. This lets a developer examine recorded content without changing the working tree.

For a regression, I would inspect the suspect commit and the exact file version it introduced before switching branches or editing anything. A merge commit's diff presentation differs from an ordinary single-parent commit, so absence of an expected patch line may require a more explicit comparison. Read-only inspection is often the safest first step in diagnosis.

14. What is a branch in Git?

A branch is a movable reference to a commit. New commits on the checked-out branch normally advance that reference, while earlier commits remain connected through parent relationships. Creating a branch does not copy every project file into an independent repository.

I would use a branch to name a line of development and keep related work separate until it is ready to integrate. The name alone does not enforce permissions or protect history; those controls usually come from repository or hosting policies. A branch can be deleted while its commits remain reachable through other references.

15. What does HEAD represent?

HEAD identifies the current checkout position, usually by referring symbolically to a branch. In detached HEAD state it points directly to a commit instead. It is not necessarily the newest commit anywhere in the repository or on the remote.

Commands that use HEAD operate relative to the current checkout, so I would confirm it before a history-changing operation. If I inspect an older commit in detached state and make useful commits, I should create a branch or another reference to retain an easy name for that work. The commits do not automatically belong to the branch I was on previously.

16. How do you create and switch branches?

Use an appropriate branch command and switch operation, such as git switch -c for a new branch from the current starting point. Switching updates the checkout to the selected branch subject to protections for local changes. It does not guarantee that every uncommitted change disappears or follows the intended feature.

I would inspect status first and decide whether current edits belong on the new branch, should be committed or should be saved separately. Git may refuse a switch that would overwrite local work. That refusal is useful evidence to resolve deliberately, not a reason to immediately force the operation.

# Start in a clean disposable repository on main.
git switch -c feature-demo
git branch --show-current
# Expected branch: feature-demo
# Start in a clean disposable repository on main.
git switch -c feature-demo
git branch --show-current
# Expected branch: feature-demo
# Start in a clean disposable repository on main.
git switch -c feature-demo
git branch --show-current
# Expected branch: feature-demo

17. What does detached HEAD mean?

Detached HEAD means the checkout is at a commit directly rather than attached to a local branch reference. It is useful for inspecting or testing historical versions. Commits can still be created, but no ordinary branch is automatically advanced to keep a convenient name for them.

If an experiment becomes valuable, I would create a branch at the current commit before moving away. If I already moved, the reflog may help locate the commit while it remains available. Detached state is not corruption; the risk is losing an easy reference to work that should have been retained.

# Start in a clean disposable repository with at least one commit.
git switch --detach HEAD
git switch -c retained-experiment
git branch --show-current
# The checkout is now attached to retained-experiment.
# Start in a clean disposable repository with at least one commit.
git switch --detach HEAD
git switch -c retained-experiment
git branch --show-current
# The checkout is now attached to retained-experiment.
# Start in a clean disposable repository with at least one commit.
git switch --detach HEAD
git switch -c retained-experiment
git branch --show-current
# The checkout is now attached to retained-experiment.

18. What is a merge?

A merge integrates histories by finding an appropriate relationship and combining changes, sometimes producing a merge commit with multiple parents. If one tip is already an ancestor of the other, a fast-forward may be possible instead. Git can combine text mechanically but cannot prove the resulting program is correct.

I would inspect the branch relationship, perform the intended merge and validate the combined behavior. Even a conflict-free merge can introduce a semantic bug when two changes affect related assumptions in different files. The integration decision should include tests and review rather than stop at Git reporting success.

19. What is a fast-forward merge?

A fast-forward moves a branch reference to a descendant commit when no divergent history needs combining. It normally creates no new merge commit because the target history already contains the current tip. Options and policy can request a merge commit or require fast-forward-only behavior.

I would use fast-forward-only integration when the workflow should reject divergence instead of choosing a reconciliation automatically. A successful fast-forward says something about ancestry, not code quality. If the team requires an explicit integration record, a different merge policy may be appropriate even when a fast-forward is technically possible.

20. What causes a merge conflict?

A conflict occurs when Git cannot resolve the requested integration automatically under the selected strategy, often because changes overlap or file operations disagree. It is not limited to two people editing the same exact line. Rename, delete and add relationships can also conflict.

I would inspect the conflict and both sides' intent, resolve the resulting file deliberately and test it before marking the path resolved. Choosing one entire side can discard valid work from the other. Conflict markers are a prompt for reasoning, not instructions that the upper or lower section is automatically correct.

21. What is a remote?

A remote is a named configuration for another repository's location and associated fetch or push behavior. Names such as origin are conventions, not special servers built into Git. A repository can have several remotes with different purposes.

I would inspect git remote -v and the relevant configuration before transferring history, especially in a fork workflow. Fetch and push URLs can differ, and a familiar remote name does not prove it points to the intended destination. Remote configuration is local metadata; adding it does not grant access or send commits by itself.

22. What does git fetch do?

git fetch retrieves objects and updates selected references according to its refspecs, commonly updating remote-tracking branches. It normally does not integrate those changes into the current local branch or overwrite its working-tree edits. It refreshes the local view needed to make an informed integration decision.

I would fetch before comparing my work with the remote when freshness matters, then inspect the resulting ancestry. Fetch can reveal that a remote branch was rewritten or removed, depending on options and configuration. A successful fetch is not the same as successfully merging or rebasing the local branch.

23. How does git pull differ from git fetch?

git pull performs a fetch and then integrates the selected upstream history using the configured or requested reconciliation behavior, such as merge or rebase. Its exact effect depends on options and configuration. Fetch alone stops before that integration step.

I would use an explicit policy when working on important branches so a pull does not unexpectedly create a merge commit or rewrite local commits. If histories diverge, inspect them before choosing the integration. Pull is convenient, but treating it as a harmless refresh obscures the fact that it can change the current branch and working tree.

24. What does git push do?

git push transfers necessary objects and asks the remote to update specified references. The remote can reject the update because of ancestry, permissions, hooks or policy. A local commit is not shared merely because it exists or because the branch has a remote-tracking name.

Before pushing, I would confirm the destination and which references will be updated. A push does not necessarily publish every local branch or tag; refspecs and configuration determine scope. Afterward, use the reported result and appropriate remote inspection to distinguish an accepted update from a failed or uncertain transfer.

25. What is a remote-tracking branch?

A remote-tracking branch is a local reference that records the remote branch state observed through fetch or related operations. It is commonly named origin/main, but it is not a live connection that changes instantly whenever someone pushes. A local development branch can track it as its upstream.

I would compare my branch with the remote-tracking reference after fetching when deciding what to integrate. Editing files while on a local branch does not directly edit origin/main. This distinction explains why ahead and behind counts can be accurate relative to the last observation yet outdated relative to the current server.

26. What does an upstream branch configure?

An upstream association tells Git which branch is related to a local branch for operations and status reporting, according to command options and configuration. It commonly links a local branch to a remote-tracking branch. It does not create a permanent guarantee that pull and push always target the same place.

I would inspect the upstream when a command reports no tracking information or compares against an unexpected branch. Fork workflows may intentionally fetch from one remote and push to another. Explicit command arguments can override defaults, so understanding the configuration is more reliable than assuming every branch tracks origin with the same name.

27. What do ahead and behind counts mean?

They count commits reachable from one compared tip but not the other, expressing divergence in the commit graph. They are not counts of changed files or a judgment about which version is better. The comparison uses the locally available references.

If a branch is ahead by two and behind by one, both sides have unique commits and integration needs a policy. I would fetch first when the remote state may have changed, then inspect the actual commits. Rebasing can change these counts even when the resulting file content is similar because commit identity and ancestry have changed.

28. How does .gitignore work?

Ignore rules influence which untracked paths Git normally presents or adds. They do not remove already tracked files from history or stop updates to a file that is already tracked. Shared project rules can live in .gitignore, while local-only exclusions have other mechanisms.

I would ignore generated files and local secrets before initial staging, then verify with status or check-ignore. If a credential was already committed, adding its path to .gitignore is not remediation. The exposed credential needs revocation or rotation and the repository history may require a coordinated cleanup.

29. How do you stop tracking a file while keeping a local copy?

Remove the path from the index with an appropriate cached removal and add an ignore rule if it should remain untracked. Commit that change so the repository no longer includes the file in the new snapshot. Earlier commits still contain it unless history is deliberately rewritten.

I would first confirm that the file truly should be local-only and consider how the removal affects collaborators checking out the new commit. Keeping my working copy is not a promise that every colleague's copy will be preserved under all operations. For shared configuration, a tracked example file plus an ignored local override is often clearer.

30. How do you unstage a change without discarding the working edit?

Use an index-targeted operation such as git restore --staged for the intended path in a repository with an appropriate source commit. It updates the staged state while leaving the working-tree edit available. This differs from restoring the working tree, which can discard uncommitted content.

I would inspect status and the staged diff afterward to confirm the intended change moved out of the next commit. The source matters, especially before the first commit or when an explicit revision is supplied. Avoid memorizing restore as a generic undo command without understanding which state it changes.

# Disposable demo: notes.txt is already tracked.
printf 'keep this edit\n' >> notes.txt
git add -- notes.txt
git restore --staged -- notes.txt
git diff --cached -- notes.txt
git diff -- notes.txt
# The staged diff is empty; the working-tree edit remains.
# Disposable demo: notes.txt is already tracked.
printf 'keep this edit\n' >> notes.txt
git add -- notes.txt
git restore --staged -- notes.txt
git diff --cached -- notes.txt
git diff -- notes.txt
# The staged diff is empty; the working-tree edit remains.
# Disposable demo: notes.txt is already tracked.
printf 'keep this edit\n' >> notes.txt
git add -- notes.txt
git restore --staged -- notes.txt
git diff --cached -- notes.txt
git diff -- notes.txt
# The staged diff is empty; the working-tree edit remains.

31. How do you discard an unstaged edit deliberately?

After reviewing and preserving any work that must be kept, restore the intended working-tree path from the chosen source. By default, git restore without --staged restores the working tree from the index. This can permanently discard content that Git never recorded elsewhere.

I would inspect the diff and use a narrow path or patch selection rather than discard the whole directory casually. If the file also has staged changes, restoring from the index retains that staged version, which may differ from HEAD. The command should follow a clear decision about the desired source, not an assumption that every undo returns to the last commit.

32. How do reset, restore and revert differ at a high level?

Restore changes selected working-tree or index contents, reset can move a branch position and optionally alter the index and working tree, and revert creates a new commit that reverses a prior change. Their effects are different, so none is a universal synonym for undo.

For a published faulty commit, a revert often preserves a comprehensible shared history. For an accidentally staged file, an index-only restore is more focused. I would identify whether the goal concerns uncommitted files, local history or shared history before choosing a command, then verify what changed.

33. What is a tag?

A tag names a particular object, commonly a release commit, and normally remains fixed rather than advancing with development. Lightweight tags are references, while annotated tags have a tag object containing additional metadata and can be signed. Tags and branches serve different lifecycle purposes.

I would use an annotated release tag when the team wants release metadata and verification policy. Creating a tag locally does not guarantee it was pushed. Moving an already shared release tag can confuse consumers and build systems, so corrections should follow the project's release process rather than silently repointing a familiar name.

34. What is git stash useful for?

Stash saves selected local changes so the working tree can be cleared for another task, with options governing untracked or ignored files. It is convenient for short-lived work but is not a substitute for a named, reviewed commit or a durable shared backup. Restoring a stash can conflict with later changes.

I would inspect what will be included and use a descriptive message when several stashes may exist. By default, untracked files are not included, so a new file can remain behind. Before dropping a stash, confirm that the needed work has been restored or recorded safely.

35. How do stash apply and stash pop differ?

Apply attempts to restore a stash while keeping the stash entry; pop attempts restoration and removes the entry when application succeeds. If pop encounters conflicts, the entry is normally retained. Neither operation guarantees that the restored result is correct or conflict-free.

I often prefer apply when I want to inspect and test the result before explicitly dropping the saved entry. Restoring the staged state may require the relevant option and can fail under conflicts. The distinction is about retention and restoration behavior, not a promise that pop can always undo itself automatically.

36. What does git rm do?

git rm stages removal of tracked paths and normally removes them from the working tree, subject to checks that protect changed content. With --cached it removes them from the index while keeping the local files. A removal commit changes the current snapshot, not every historical version.

I would review the paths and staged diff before committing a deletion, particularly when a generated file and a source file have similar names. Deleting a file in the editor and staging its removal can achieve the same resulting snapshot. The important outcome is the index state, not which user interface performed the filesystem deletion.

37. How does Git recognize a renamed file?

Git stores snapshots and commonly detects renames by comparing deleted and added content during diff or merge processing. A rename is not generally a permanent special link recorded in each commit. Similarity thresholds and the extent of edits can affect detection.

I would use git mv for convenience, but understand that a filesystem move followed by appropriate staging can record an equivalent snapshot. Large simultaneous rewrites can make history harder to follow even when the move is intentional. Separating a mechanical move from behavioral edits can improve review when the repository workflow permits it.

38. What are author and committer identities?

The author identifies the person credited with creating the change, while the committer identifies the person or process that recorded that commit object. They can differ during operations such as applying patches or rebasing. These metadata fields are not by themselves cryptographic proof of identity.

I would configure the intended identity at the appropriate scope and inspect it before contributing to a project. Rebasing may preserve authorship while changing committer information and the commit identifier. Hosting-platform account association and signed-commit verification add separate rules beyond the names and email addresses stored in the object.

39. How do configuration scopes affect Git behavior?

Git reads configuration from several scopes, including system, user and repository locations, with more specific settings generally overriding broader ones. Command-line configuration can affect one invocation. The effective value may therefore differ between repositories or automation environments.

When behavior surprises me, I would inspect the value and its origin rather than change global settings immediately. A repository-specific identity or pull policy can be intentional. Avoid writing credentials into ordinary configuration output or changing a user's global defaults as a shortcut for one isolated test.

40. What should you inspect before changing repository history?

Inspect status, the current branch or detached position, recent history, relevant remote state and whether work has been shared. Identify the exact commits and the desired resulting graph. Preserve useful work with an appropriate reference or backup before an operation that can make it harder to reach.

I would distinguish uncommitted changes from committed history because recovery options differ. A reflog can help with some moved references, but it does not reliably recover every untracked edit or act as a permanent backup. A deliberate history change ends with validation of the resulting content and collaboration impact, not just a successful command exit.

Git Interview Questions and Answers for Intermediate

These answers connect commands to their preconditions, resulting history and practical verification steps.

41. How can you stage only part of a file?

Use patch-based staging, such as git add -p, to select the hunks that belong in the next commit. The index can then contain a different version from the full working tree. Review the staged diff afterward because hunk selection is a means of constructing a coherent snapshot, not proof that the snapshot builds.

If one file contains a bug fix and an unrelated cleanup, I would stage the fix separately when the resulting intermediate version remains valid. Tests run against the working tree may include unstaged changes, so they may not validate the exact staged snapshot. For important separation, test that snapshot in an isolated checkout or another appropriate workflow.

42. What does amending a commit change?

git commit --amend creates a replacement commit using the intended index and metadata, rather than editing the existing object in place. The new identifier can differ even if only the message changes. Other references to the old commit are not automatically rewritten everywhere.

I would amend an unpublished local commit to correct a message or include a missing related change, then inspect the result. If the commit is already shared, coordinate before replacing it because collaborators may have based work on the old identity. A subsequent push may require a deliberate non-fast-forward update subject to policy.

43. How do soft, mixed and hard reset modes differ?

In the common commit-target form, soft reset moves the current branch position while preserving the index and working tree; mixed also resets the index; hard also resets tracked working-tree content to the target. Hard reset can discard local work and can remove untracked paths that obstruct writing tracked paths. Path-based reset has different behavior and does not move the branch.

I would choose a mode only after naming the desired states of HEAD, index and files. For regrouping local commits, soft or mixed may preserve the content needed for new commits. A hard reset should never be described as a harmless way to refresh a branch when unrecorded work may exist.

# Disposable demo only: create one local commit to regroup.
printf 'local change\n' >> notes.txt
git add -- notes.txt
git commit -m 'Local change to regroup'
git branch before-regroup
git reset --soft HEAD~1
git diff --cached -- notes.txt
# Branch position moved; the change is still staged.
# before-regroup retains a reference to the original commit.
# Disposable demo only: create one local commit to regroup.
printf 'local change\n' >> notes.txt
git add -- notes.txt
git commit -m 'Local change to regroup'
git branch before-regroup
git reset --soft HEAD~1
git diff --cached -- notes.txt
# Branch position moved; the change is still staged.
# before-regroup retains a reference to the original commit.
# Disposable demo only: create one local commit to regroup.
printf 'local change\n' >> notes.txt
git add -- notes.txt
git commit -m 'Local change to regroup'
git branch before-regroup
git reset --soft HEAD~1
git diff --cached -- notes.txt
# Branch position moved; the change is still staged.
# before-regroup retains a reference to the original commit.

Mode, commit-target form

Branch position

Index

Tracked working tree

--soft

Moves to target

Preserved

Preserved

--mixed

Moves to target

Reset to target

Preserved

--hard

Moves to target

Reset to target

Reset to target; local work can be lost

44. When is revert preferable to rewriting history?

Revert records a new change that reverses an earlier commit's effect while retaining the existing history. It is often appropriate for a shared branch because collaborators can integrate it through ordinary forward-moving history. Reverting may conflict and does not necessarily restore the entire project to an older snapshot.

For a faulty published feature, I would identify the relevant commit or commits, create the reversal and test the resulting behavior. Later changes may depend on the reverted work, so a mechanical reversal can still break the application. A revert documents a new decision; it does not erase the original commit or any secret it contained.

# Disposable demo with a clean tracked notes.txt.
printf 'faulty addition\n' >> notes.txt
git add -- notes.txt
git commit -m 'Add demonstration change'
git revert --no-edit HEAD
git log -2 --oneline
# A new reversal commit exists; the original commit remains in history.
# Disposable demo with a clean tracked notes.txt.
printf 'faulty addition\n' >> notes.txt
git add -- notes.txt
git commit -m 'Add demonstration change'
git revert --no-edit HEAD
git log -2 --oneline
# A new reversal commit exists; the original commit remains in history.
# Disposable demo with a clean tracked notes.txt.
printf 'faulty addition\n' >> notes.txt
git add -- notes.txt
git commit -m 'Add demonstration change'
git revert --no-edit HEAD
git log -2 --oneline
# A new reversal commit exists; the original commit remains in history.

45. How do merge and rebase differ?

Merge combines histories while retaining their existing commits and may add a multi-parent commit. Rebase replays selected changes onto a new base, usually creating new commit identities and a different graph. Both can conflict, and neither is inherently correct for every team workflow.

I would use the repository's policy and whether the branch is shared to choose between them. Rebasing a private feature can make its sequence easier to review, while merging can preserve an explicit integration relationship. The decision should be about the desired history and collaboration contract, not an assumption that linear history guarantees better code.

46. How do you resolve a rebase conflict?

Inspect the stopped commit and conflict, edit the files to represent the intended result on the new base, stage the resolution and continue the rebase. Abort returns toward the pre-rebase state when that is the appropriate choice. Skipping a commit omits its change and should not be used merely to make the conflict disappear.

I would understand which change is being replayed and which base it is replayed onto before choosing either side. Rebase may stop several times because commits are applied separately. After completion, compare the revised series and test the final result, including whether any important change was accidentally lost during conflict resolution.

47. What can interactive rebase do?

Interactive rebase can reorder, combine, edit or drop selected commits according to a planned sequence. It is useful for preparing local history for review, but changes commit identities and may alter dependencies between commits. The selected range must include exactly the history intended for revision.

I would create a recovery reference and inspect the proposed sequence before editing it. Reordering a setup change after its consumer can make intermediate commits invalid even if the final tree looks right. Shared branches need coordination, and a polished sequence should still preserve the meaningful reasoning and tests rather than merely minimize the commit count.

48. How do fixup commits and autosquash work together?

A fixup commit identifies an earlier commit whose change it is intended to amend, and an autosquash-enabled interactive rebase can arrange the fixup beside its target with the appropriate operation. This supports incremental review while later producing a coherent history. The target must be within the selected rebase range.

I would use a fixup for a focused correction to an existing local series, then inspect the autosquash plan before applying it. It is not automatic remote history cleanup, and ambiguous or changed subjects can require attention. After rewriting, verify both final content and commit structure so the correction did not attach to the wrong logical change.

49. How do you split one local commit into several coherent commits?

Use an editing workflow that returns the selected commit's changes to a staged or unstaged state, then stage and commit coherent subsets before continuing any surrounding rebase. Preserve a recovery reference first and understand whether later commits depend on the one being split. The goal is valid, reviewable intermediate snapshots.

I would separate behavior from an unrelated refactor only when each new commit remains understandable and testable. Patch staging can help, but a partial file state may not compile. Validate each important new boundary in an isolated checkout and avoid splitting already shared history without the collaboration agreement required by the repository.

50. What does cherry-pick do?

Cherry-pick applies the change introduced by a selected commit onto the current branch and normally creates a new commit. It does not move the original commit or automatically bring all its prerequisites. On a different parent, the resulting identifier differs; metadata and conflict resolution can also change it.

For a maintenance fix, I would inspect dependencies and choose the smallest complete change set, then test it on the older branch. A clean cherry-pick can still be semantically wrong if the old code has different assumptions. Recording the source commit where the workflow expects it helps later maintainers understand the relationship.

# Start clean on main in a disposable repository.
git switch -c fix-source
printf 'portable fix\n' > fix.txt
git add -- fix.txt
git commit -m 'Add portable fix'
source_commit=$(git rev-parse HEAD)
git switch main
printf 'target context\n' > target-context.txt
git add -- target-context.txt
git commit -m 'Establish target context'
git cherry-pick "$source_commit"
# Inspect the resulting commit and test its behavior on the target branch.
# Start clean on main in a disposable repository.
git switch -c fix-source
printf 'portable fix\n' > fix.txt
git add -- fix.txt
git commit -m 'Add portable fix'
source_commit=$(git rev-parse HEAD)
git switch main
printf 'target context\n' > target-context.txt
git add -- target-context.txt
git commit -m 'Establish target context'
git cherry-pick "$source_commit"
# Inspect the resulting commit and test its behavior on the target branch.
# Start clean on main in a disposable repository.
git switch -c fix-source
printf 'portable fix\n' > fix.txt
git add -- fix.txt
git commit -m 'Add portable fix'
source_commit=$(git rev-parse HEAD)
git switch main
printf 'target context\n' > target-context.txt
git add -- target-context.txt
git commit -m 'Establish target context'
git cherry-pick "$source_commit"
# Inspect the resulting commit and test its behavior on the target branch.

51. Why can ours and theirs be confusing during a rebase?

The labels describe sides of the operation rather than permanently meaning my work and someone else's work. During a rebase, the already rebased base side and the commit being replayed can make the intuitive ownership labels seem reversed. The exact command context matters.

I would inspect the base, current side and replayed change instead of selecting an entire side based on personal ownership. Conflict resolution should preserve the intended combined behavior. A team explanation should identify actual commit IDs or branch roles, because saying keep ours can be dangerously ambiguous across merge and rebase workflows.

52. How can you inspect the three stages of an unresolved merge?

The index can hold separate entries for the merge base and the two sides of an unresolved path. Commands such as git ls-files -u and revision syntax for index stages let you inspect those versions. Not every conflict has all three stages, for example in certain add or delete cases.

I would compare the relevant versions when conflict markers omit context or a binary file cannot show a textual merge. Stage numbers are operation-specific evidence, not a judgment about which side should win. After resolving and staging the final file, confirm that no unmerged entries remain and that the result satisfies the actual feature requirements.

53. What does git merge --abort attempt to do?

It attempts to stop an in-progress merge and reconstruct the pre-merge state. Existing uncommitted changes can complicate recovery, especially if they were modified further during the conflict. This is why understanding and preserving local work before integration matters.

I would inspect status before and after abort and verify that the work I intended to keep is present. Do not assume abort is a universal undo for unrelated commands or edits performed since the merge began. If recovery is uncertain, preserve the current files separately before experimenting with additional destructive operations.

54. How does git reflog help recover a moved branch or detached commit?

Reflogs record local reference movements, allowing a developer to find previous positions such as a branch tip before a reset or a detached commit before switching away. Once identified, creating a new branch at the commit can make it reachable through a durable name. Reflogs are local and expire according to policy.

I would inspect the relevant reflog and verify the candidate commit before moving an important branch back. A reflog entry is not guaranteed to exist in another clone, and unreferenced objects can eventually be pruned. It helps recover recorded Git objects, not every file edit that was never staged or committed.

# Disposable demo: preserve an intentionally moved local commit.
printf 'recoverable change\n' >> notes.txt
git add -- notes.txt
git commit -m 'Recoverable demonstration'
git reset --soft HEAD~1
git reflog -2 --format='%h %gs'
git branch recovered-demo 'HEAD@{1}'
git show recovered-demo:notes.txt
# The branch makes the former tip easy to reach again.
# Disposable demo: preserve an intentionally moved local commit.
printf 'recoverable change\n' >> notes.txt
git add -- notes.txt
git commit -m 'Recoverable demonstration'
git reset --soft HEAD~1
git reflog -2 --format='%h %gs'
git branch recovered-demo 'HEAD@{1}'
git show recovered-demo:notes.txt
# The branch makes the former tip easy to reach again.
# Disposable demo: preserve an intentionally moved local commit.
printf 'recoverable change\n' >> notes.txt
git add -- notes.txt
git commit -m 'Recoverable demonstration'
git reset --soft HEAD~1
git reflog -2 --format='%h %gs'
git branch recovered-demo 'HEAD@{1}'
git show recovered-demo:notes.txt
# The branch makes the former tip easy to reach again.

55. What does ORIG_HEAD represent?

ORIG_HEAD is a reference used by certain operations to record the prior HEAD position, often providing a convenient starting point for recovery. Its value can be overwritten by later commands, so it is not a permanent history of every operation. Reflogs provide a broader local record where available.

After an unexpected integration, I would inspect ORIG_HEAD rather than blindly reset to it. Confirm the commit and preserve current work before using it as a recovery target. A documented command sequence should explain which operation established the value, because an unrelated later reset or merge may have changed its meaning.

56. How do you compare a feature branch with its base?

Choose the comparison that answers the question: a two-endpoint diff compares their final trees, while a three-dot diff commonly compares the merge base with the selected branch tip. Commit-range notation in log has different set semantics from diff. The punctuation should not be treated as one universal operation across commands.

For review, I often want the feature's changes since its divergence point, then separately inspect integration with the current target. A two-tip comparison may include changes made only on the target and obscure the feature's contribution. I would name the intended endpoints explicitly and verify the merge base when the history is unusual.

# Disposable demo: independent changes on two branches.
git switch -c feature-compare
printf 'feature\n' > feature.txt
git add -- feature.txt
git commit -m 'Feature change'
git switch main
printf 'target\n' > target.txt
git add -- target.txt
git commit -m 'Target change'
git diff --name-status main feature-compare
git diff --name-status main...feature-compare
# Two tips differ in both files; three-dot shows the feature since the base.
# Disposable demo: independent changes on two branches.
git switch -c feature-compare
printf 'feature\n' > feature.txt
git add -- feature.txt
git commit -m 'Feature change'
git switch main
printf 'target\n' > target.txt
git add -- target.txt
git commit -m 'Target change'
git diff --name-status main feature-compare
git diff --name-status main...feature-compare
# Two tips differ in both files; three-dot shows the feature since the base.
# Disposable demo: independent changes on two branches.
git switch -c feature-compare
printf 'feature\n' > feature.txt
git add -- feature.txt
git commit -m 'Feature change'
git switch main
printf 'target\n' > target.txt
git add -- target.txt
git commit -m 'Target change'
git diff --name-status main feature-compare
git diff --name-status main...feature-compare
# Two tips differ in both files; three-dot shows the feature since the base.

Command form

Question it answers

git diff A B

How do the two endpoint trees differ?

git diff A...B

How does B differ from the merge base of A and B?

git log A..B

Which commits are reachable from B but not A?

git log A...B

Which commits are reachable from either side but not both?

57. What is a merge base?

A merge base is a best common ancestor used to understand how histories diverged and to support integration or comparison. Complex graphs can have more than one best merge base. It is not necessarily the commit where a human remembers creating the branch.

I would use merge-base when interpreting a review diff or planning a rebase rather than assume a fixed number of commits back from HEAD. Merges and rebases can change the graph relationship. The chosen base influences which changes are attributed to each side, so an incorrect assumption can lead to an incomplete or misleading comparison.

58. How do you respond to a non-fast-forward push rejection?

Inspect the remote state and the local graph to understand why the proposed update would not simply advance the remote reference. Fetching and integrating another contributor's work may be the right response. A rejection is not automatically a reason to force push.

I would compare the commits and determine whether the remote advanced normally or the local branch was intentionally rewritten. If a rewrite is authorized, use a controlled update under the repository's policy and verify the expected remote tip. Otherwise integrate the missing work and test before pushing again, preserving contributions that appeared while I was working.

59. What protection does force-with-lease provide?

A lease makes a forced reference update conditional on the remote having an expected value, reducing the risk of overwriting an update you did not intend to replace. It is still a history rewrite and must be authorized by the workflow. Implicit expectations based on remote-tracking references can be affected by background fetches.

For a carefully coordinated rewrite, an explicit expected object ID provides a clearer condition than assuming a local tracking ref has not moved. I would inspect and communicate the intended replacement and avoid treating the option as permission to rewrite any shared branch. A successful lease check does not prove nobody depends on the old history.

60. How does a remote default branch differ from origin/HEAD and the current local branch?

The remote repository advertises a default branch through its HEAD, while origin/HEAD is a local symbolic reference naming the corresponding remote-tracking branch. Your own HEAD identifies the current local checkout. These references serve different purposes: changing a server default does not automatically rename or switch the branch where you are working.

After a default-branch migration, I would inspect the remote advertisement and fetched branches, then deliberately refresh the local shortcut with git remote set-head origin -a when its target exists locally. This updates origin/HEAD, not the server default or local branch upstream settings. Scripts should use an explicit intended branch or resolve the default deliberately instead of assuming every repository uses main.

61. How do you delete a local branch safely?

Inspect whether the branch contains work that must remain reachable, then use the normal checked deletion behavior when appropriate. The safe deletion check uses Git's merge and upstream rules, which should not be confused with a human review of all valuable work. Forced deletion bypasses that protection.

I would verify the integration destination and preserve an explicit reference if uncertain. Deleting the branch name does not immediately erase every referenced object, but relying on eventual reflog recovery is weaker than making the preservation decision first. A branch checked out in another worktree also needs lifecycle attention before removal.

62. How does pruning remote-tracking references differ from deleting remote branches?

Pruning removes local references that no longer correspond to the fetched remote's advertised references according to the refspec. Deleting a remote branch asks the server to remove that branch. These are different scopes and consequences.

I would use a prune operation to clean a stale local view after confirming the remote configuration, not as a method for deleting colleagues' branches. Tags and unusual refspecs can change what pruning covers, so inspect options before applying it broadly. A tidy local branch list does not itself prove that the remote repository was changed.

63. How are tags transferred to a remote?

Tags can be pushed explicitly, and options such as follow-tags or tags have different scope. A normal branch push does not mean every local tag is transferred. Annotated and lightweight tags also differ in which automatic-following behavior applies.

For a release, I would identify the exact tag and target commit, verify it and push only the intended references. Broadly pushing all tags can publish unrelated local labels. Afterward, confirm the remote tag according to the release process, because a local tag's existence is not evidence that consumers can fetch it.

64. What are signed commits and tags useful for?

A signature can let a verifier check that the signed object was approved by a particular key under the verifier's trust policy. It adds integrity and identity evidence beyond freely editable author metadata. It does not establish that the code is correct, safe or approved under every organizational rule.

I would distinguish cryptographic verification from trusting the key's ownership and authorization. Key rotation, expiration and allowed-signers policy affect verification over time. Signing a release tag can identify the exact release object, but the build and artifact provenance still need their own chain of evidence.

65. How does git bisect locate a regression?

Bisect narrows a range between known good and bad commits by testing selected candidates. It relies on a meaningful, sufficiently repeatable classification of the behavior. The first bad commit in the tested graph is evidence about introduction, not necessarily a complete explanation of the root cause.

I would create a focused test and ensure each candidate can be built under suitable dependencies. If a commit cannot be tested, mark it skipped rather than incorrectly good or bad. Flaky tests and changing external services can mislead the search, so stabilize the environment and verify the final candidate before assigning blame.

66. How can git blame be used responsibly?

Blame attributes lines to commits according to its traversal and options, helping locate relevant history. It does not identify who is responsible for a bug in the broader design, and mechanical moves or formatting changes can affect the result. Use it as a starting point for investigation.

I would inspect the attributed commit and surrounding history, including the reason the code was introduced. Options for movement or ignored revisions can improve the signal when a formatter touched many lines. A regression may come from a changed caller or requirement elsewhere, so the last editor of a line is not automatically the cause.

67. When is log -S different from log -G?

The pickaxe options answer related but different history questions: -S searches for changes in the number of occurrences of a string or pattern under its options, while -G searches patch lines matching a regular expression. A textual move or rewrite can therefore appear differently in each search.

If I want to find when a named configuration key was introduced or removed, -S may be useful; if I want commits whose changed lines match a code pattern, -G may fit better. I would inspect the returned patches and consider rename or path filters. No single text search proves the complete semantic history of a feature.

68. How do pathspecs and the double-dash separator prevent command ambiguity?

A pathspec selects paths for a Git operation, while the double-dash separator can distinguish path arguments from revisions or options where the command supports that syntax. Quoting also matters because the shell may expand patterns before Git sees them. The exact command grammar determines the effect.

For a file whose name resembles a branch or begins with a dash, I would use the documented separator and a narrow quoted pathspec. This prevents a command from interpreting the input as a different kind of argument. Scripts should use robust filename handling, including null-delimited output where appropriate, rather than assume paths never contain spaces or newlines.

# Disposable demo: a filename that resembles an option.
printf 'ordinary file\n' > ./--help
git add -- ./--help
git diff --cached -- ./--help
# -- separates this path from command options.
# Disposable demo: a filename that resembles an option.
printf 'ordinary file\n' > ./--help
git add -- ./--help
git diff --cached -- ./--help
# -- separates this path from command options.
# Disposable demo: a filename that resembles an option.
printf 'ordinary file\n' > ./--help
git add -- ./--help
git diff --cached -- ./--help
# -- separates this path from command options.

69. How do line-ending policies affect collaboration?

Git attributes and configuration can normalize text in the repository and control checkout line endings. A shared .gitattributes policy is often clearer than relying solely on each developer's global settings. Misaligned policies can produce noisy diffs or inconsistent executable behavior.

I would define the intended treatment for text and binary files, then perform any normalization as a focused, reviewed change. Mixing mass line-ending conversion with a bug fix makes review and blame harder. Test scripts on the relevant platforms and avoid applying text conversion blindly to binary formats.

70. What can .gitattributes control beyond line endings?

Attributes can influence diff and merge behavior, filters, archive behavior and other path-specific treatment. They describe how Git should handle matching paths, not arbitrary application runtime configuration. Some behaviors also require local or repository configuration and installed tooling.

For generated or binary assets, an appropriate diff treatment can make reviews clearer without pretending the content was semantically reviewed. A custom filter introduces another dependency that can affect checkout and staging. I would document and test that setup across environments rather than assume an attributes file alone installs the required program.

71. What are Git hooks, and where should enforcement live?

Hooks are scripts run at defined points in Git operations, such as before a commit or when a server receives updates. Client-side hooks can improve feedback but can be absent or bypassed, so important shared policy usually needs server or CI enforcement. Hook installation is not automatically guaranteed by cloning ordinary tracked files.

I would keep fast local checks useful and reproducible, with authoritative validation in the collaboration system where required. A hook that modifies files can change what needs to be staged or reviewed, so its behavior should be explicit. Never assume a successful local commit proves every organizational check ran.

72. How do patches differ from bundles?

A patch represents changes that can be applied, with formats that may include commit metadata for tools such as format-patch and am. A bundle packages Git objects and references for repository transfer, potentially with prerequisites. They solve different offline collaboration needs.

I would use a patch series when review and application of individual changes is the goal, and a bundle when transferring a section of repository history without a network remote. Verify prerequisites and contents before relying on a bundle as a backup. Neither format automatically includes untracked working files or hosting-service metadata.

73. How do git apply and git am differ?

git apply applies patch changes to files or the index according to options and does not normally create commits. git am applies mailbox-style patch messages and creates commits using their metadata. Choosing the wrong tool can lose the intended commit structure or fail to interpret the input format.

I would inspect the patch source, check applicability and preserve current work before applying it. A patch applying cleanly does not prove it is appropriate or safe. After application, review the resulting diff and run relevant tests rather than treating successful textual application as complete integration.

74. What does a squash merge preserve and omit?

A squash integration prepares the combined content change from another branch without recording the original branch's commits as merge parents in the resulting ordinary commit. It can produce a concise target history, but the ancestry relationship differs from a true merge. The original commits still exist where referenced.

I would use it when the team wants one coherent integration commit and understands the consequences for later merges or continuing the source branch. Repeatedly merging the same long-lived branch after squashing can be confusing because Git does not see the prior source commits as ancestors through that squash commit. Content equivalence is not ancestry equivalence.

75. What is a worktree useful for?

A linked worktree provides another checkout associated with the same repository object store and shared references, with its own checkout state. It lets a developer work on another branch without stashing the first worktree's edits. It is lighter than a separate full clone but is not completely independent repository metadata.

I would use one for a review or urgent fix while preserving the current task's files. The same branch is normally prevented from being checked out in multiple worktrees to avoid conflicting updates. Remove or move worktrees through supported commands so administrative metadata stays consistent, and inspect local changes before cleanup.

# Disposable demo; ../review-checkout must not already exist.
git worktree add -b review-demo ../review-checkout HEAD
git worktree list
# A second checkout exists without switching this working tree.
# Inspect it before later removing it with git worktree remove.
# Disposable demo; ../review-checkout must not already exist.
git worktree add -b review-demo ../review-checkout HEAD
git worktree list
# A second checkout exists without switching this working tree.
# Inspect it before later removing it with git worktree remove.
# Disposable demo; ../review-checkout must not already exist.
git worktree add -b review-demo ../review-checkout HEAD
git worktree list
# A second checkout exists without switching this working tree.
# Inspect it before later removing it with git worktree remove.

76. How do submodules record dependencies?

A submodule is a separate Git repository whose selected commit is recorded by the parent through a gitlink, with location metadata commonly in .gitmodules. Updating the submodule checkout alone does not update the parent commit until the changed gitlink is staged and committed. The two repositories have separate histories.

I would verify both the submodule's intended commit and the parent reference during review. A fresh clone may need explicit submodule initialization according to options. Access, uncommitted changes and unavailable referenced commits can complicate builds, so dependency retrieval should be tested from a clean environment rather than only an existing developer checkout.

77. How do shallow clones affect history operations?

A shallow clone intentionally limits available ancestry. Operations that depend on older commits or merge bases may give incomplete results or require fetching more history. It can reduce transfer cost, but the missing history is a real constraint rather than a transparent optimization for every workflow.

For CI that only builds a tip, shallow history may be sufficient; for release-note generation or merge-base comparisons, it may not be. I would inspect the clone depth and deepen or unshallow deliberately when the task requires it. A missing ancestor in a shallow clone does not prove the remote repository lacks that commit.

78. How do sparse checkout and partial clone differ?

Sparse checkout limits which tracked paths are populated in the working tree, while partial clone can omit selected objects until needed according to filters and server support. They address different costs and can be combined. Sparse checkout alone does not necessarily reduce the repository's object history.

For a large repository, I would identify whether disk use, transfer time or working-tree size is the bottleneck before choosing options. Tools that assume every file is present may need adjustment under sparse checkout. Partial clones may require network access later, so an apparently complete initial checkout does not guarantee fully offline access to all historical content.

Mechanism

Primarily limits

Important consequence

Shallow clone

Available ancestry

Older history or merge bases may be missing

Partial clone

Initially transferred objects

Later operations may need the remote

Sparse checkout

Paths populated in the working tree

Absent files may affect tools and builds

79. Why should git clean be used cautiously?

git clean removes untracked content according to its options, and that content may never have been recorded in Git. Preview the exact scope with a dry run and inspect ignored-file options carefully before any removal. Reflog recovery generally does not help with files that were never stored as objects.

I would use narrow paths and a disposable build directory where possible rather than a broad clean at the repository root. Generated output and valuable local notes can both be untracked. A build instruction that requires cleanup should explain what is removed and why, instead of presenting a destructive command as routine status maintenance.

80. How do you validate that a rewritten patch series still contains the intended changes?

Compare the old and new series with tools such as range-diff, inspect the resulting trees and run relevant tests. Commit IDs necessarily change under many rewrites, so identity equality is not the right criterion. Range-diff helps review how individual patches changed, but it is not a semantic correctness proof.

I would preserve the old tip under a temporary reference before rewriting and examine any unexpected additions, omissions or conflict-resolution changes. A final tree comparison may miss a broken intermediate commit that the workflow expects to build. Validation should therefore cover both the final behavior and the history properties that motivated the rewrite.

Git Interview Questions and Answers for Experienced

The experienced answers examine where local command success differs from system-wide correctness, durability or trust.

81. How do blobs, trees, commits and tag objects relate?

A blob stores file content, a tree associates names and modes with blobs or subtrees, a commit references a tree and its parents, and an annotated tag object adds metadata around a referenced object. This object model separates content from paths and history. Branch names are references rather than a fifth kind of content object.

I would use this model to explain why identical content can be shared and why a rename does not require a permanent rename record in the commit. A blob alone does not tell you its filename or who introduced it. Those relationships come from trees and commits, which matters during low-level inspection or recovery.

# Read-only object inspection in any repository with a commit.
git cat-file -t HEAD
git cat-file -p HEAD
git ls-tree HEAD
# Commit metadata names a tree and any parents; the tree lists entries.
# Read-only object inspection in any repository with a commit.
git cat-file -t HEAD
git cat-file -p HEAD
git ls-tree HEAD
# Commit metadata names a tree and any parents; the tree lists entries.
# Read-only object inspection in any repository with a commit.
git cat-file -t HEAD
git cat-file -p HEAD
git ls-tree HEAD
# Commit metadata names a tree and any parents; the tree lists entries.

82. How do symbolic references differ from direct references?

A direct reference identifies an object, while a symbolic reference points to another reference name. HEAD commonly points symbolically to the current branch, which then identifies a commit. In detached state HEAD identifies a commit directly instead.

I would inspect symbolic-ref or the relevant reference through supported Git commands when diagnosing checkout behavior. Editing reference files manually can ignore packed refs, worktree-specific state or locking rules. Understanding the distinction helps explain why committing normally advances a branch but committing detached advances only the detached checkout position.

83. Why does changing a commit's parent change its identifier even when its files are unchanged?

The commit object includes its parent identifiers as well as its tree and metadata. Changing the parent changes the object content and therefore its identifier, even when the referenced tree is identical. Rebasing can consequently replace a whole descendant chain after changing one earlier commit.

I would distinguish tree equality from commit equality when comparing a rewrite. Two tips can produce identical checkouts but represent different historical relationships and signatures. This is why a force update cannot be judged solely by a zero file diff: collaborators and release records may depend on the original commit graph.

84. Why are commit timestamps insufficient for determining ancestry?

Ancestry is defined by parent links, not by chronological sorting of author or committer timestamps. Clocks can be wrong, metadata can be preserved or changed, and a graph can contain parallel histories. A later timestamp does not prove that one commit contains another.

I would use ancestry queries such as merge-base --is-ancestor when a deployment or merge decision depends on reachability. Sorting log output by time can be useful for browsing but should not implement a correctness rule. This distinction is especially important after rebases, imported patches or work created on machines with different clock settings.

# Disposable demo with an existing base commit.
base_commit=$(git rev-parse HEAD)
printf 'descendant\n' > descendant.txt
git add -- descendant.txt
git commit -m 'Create descendant'
git merge-base --is-ancestor "$base_commit" HEAD
# Exit status 0 establishes this ancestry relationship.
# Disposable demo with an existing base commit.
base_commit=$(git rev-parse HEAD)
printf 'descendant\n' > descendant.txt
git add -- descendant.txt
git commit -m 'Create descendant'
git merge-base --is-ancestor "$base_commit" HEAD
# Exit status 0 establishes this ancestry relationship.
# Disposable demo with an existing base commit.
base_commit=$(git rev-parse HEAD)
printf 'descendant\n' > descendant.txt
git add -- descendant.txt
git commit -m 'Create descendant'
git merge-base --is-ancestor "$base_commit" HEAD
# Exit status 0 establishes this ancestry relationship.

85. What does it mean for an object to be reachable?

An object is reachable when it can be found by following the relevant reference and object links from roots considered by Git's operation. Commits lead to parents and trees, and trees lead to content. An object can still exist physically after losing an ordinary branch reference, but its retention is not guaranteed forever.

I would create an explicit reference to valuable recovered work rather than rely on the object merely being present today. Reflogs and retention rules can temporarily protect objects under applicable policies. Reachability explains both recovery opportunities and why deleting a branch does not instantly erase every byte associated with it.

86. How do garbage collection and reflog expiry affect recovery?

Maintenance can compact storage and eventually remove unreachable objects according to expiry and pruning rules. Reflogs themselves also expire. Recovery methods that work immediately after a reset may therefore stop working later, especially after aggressive cleanup.

I would avoid running pruning or cleanup while investigating missing history and preserve candidate objects under references first. Do not describe reflog as an unlimited undo log or recommend immediate aggressive garbage collection to reduce size after an incident. Backups and deliberate retention policies are needed when history recovery has business importance.

87. What can git fsck establish?

git fsck checks object connectivity and validity according to its options and can report missing, corrupt or dangling objects. It is useful for repository diagnosis, but does not prove that the application code is correct or that every expected business commit is present. A valid repository can still be the wrong repository or an incomplete intended backup.

I would preserve the original evidence before attempting repair, compare with trusted copies and inspect reported objects carefully. A dangling commit may be valuable recoverable work or harmless abandoned history. Treat the diagnostic as input to a recovery plan, not an instruction to delete everything that lacks a current branch name.

88. How do packfiles and delta compression affect Git's snapshot model?

Git logically records snapshots through objects, while packfiles can store objects efficiently using compression and deltas. The storage optimization does not mean a commit's logical content is merely a mutable patch against the previous commit. Git reconstructs the required objects when reading them.

I would separate conceptual history from physical storage when explaining performance or recovery. Repacking can change storage layout without changing commit identities. Large frequently changing binary files may still be expensive because their history accumulates and compresses differently from text, so repository design should consider actual asset behavior.

89. What are replacement references, and why can they complicate investigation?

Replacement references can make Git commands substitute one object for another during history traversal, altering the view of history without rewriting the original objects in the ordinary way. They are useful for specialized repair or experimentation, but can surprise tools or investigators who assume they see the unmodified graph.

I would check for replacements when ancestry or displayed content differs unexpectedly between environments and use the documented mechanism to inspect without replacements where necessary. Do not treat a local replacement as a shared permanent repair unless the workflow explicitly distributes and understands it. Preserve the original object evidence while evaluating the intended correction.

90. What should happen after a secret is committed?

Revoke or rotate the exposed credential promptly and assess where it may have been copied. Removing the file in a later commit or adding an ignore rule does not remove earlier exposure. History cleanup, when required, is a coordinated repository operation with consequences for clones, references, caches and collaborators.

I would use the organization's incident process and a reviewed filtering workflow rather than improvise a broad rewrite. After cleanup, verify relevant references and prevent recurrence with appropriate secret management and checks. Even a successful history rewrite cannot guarantee that nobody retained the secret, which is why credential invalidation is the first security action.

91. What does Git LFS change about large-file storage?

Git LFS stores a small pointer in Git while large content is managed through an LFS object service and client integration. It can improve the handling of large assets, but adds retrieval, authentication and retention dependencies. A repository containing pointers alone is not a complete offline copy of the asset contents.

I would verify that collaborators and CI install the required tooling and can fetch the referenced objects. Moving existing large-file history to LFS is a separate migration, not something accomplished merely by adding a new tracking rule. Backups must include the needed LFS content and service policy, not only ordinary Git objects.

92. How would you investigate an unexpectedly large repository?

Measure object and pack sizes, identify large blobs and repeated binary history, and distinguish working-tree size from repository storage. A large current file is not always the dominant historical cost. Unreachable objects and extra references can also affect what remains stored or transferred.

I would inspect before rewriting, because history filtering can disrupt collaborators and release references. For future growth, adjust asset storage or generation policy where appropriate. A local size reduction after pruning does not prove that the remote or other clones are smaller, and it should not be pursued during a recovery investigation that still needs those objects.

93. Which worktree state is shared, and why does it matter?

Linked worktrees share the repository's object storage and many references, while each has its own HEAD, index and checkout-related state. Some configuration can be worktree-specific when the supported mechanism is enabled. They provide separate files, not complete isolation from every repository-level operation.

I would coordinate branch creation, deletion and history updates across active worktrees and avoid changing shared configuration casually. A fetch in one worktree can update remote-tracking references observed by another, which matters for implicit leases. Parallel tasks should have clear branch ownership even when their working directories are separate.

94. Why does reverting a merge require choosing a mainline parent?

A merge has multiple parents, so Git needs to know which parent's perspective defines the change to reverse. The mainline parent number identifies that baseline; it is not a request to keep or delete a branch by name. Choosing the wrong parent can reverse a very different set of changes.

I would inspect the merge's parent order and compare its tree with the intended parent before reverting. The new revert commit preserves the original merge in ancestry. Test the resulting behavior and explain the choice in review, because future integration decisions can be affected by the fact that the original branch's commits remain recorded as merged.

95. Why may merging a branch again after reverting its merge not restore the old changes?

The original merge remains in ancestry after a revert, so Git still considers the previously merged commits part of the target's history. A later merge normally brings new changes relative to that graph, not an automatic replay of everything that the revert removed. Content reversal and ancestry reversal are different concepts.

I would inspect whether the desired recovery is to revert the revert, add a corrected new change or rebuild the feature on an appropriate base. Each has different consequences and may conflict with later work. Do not force a repeated merge and assume it reconstructs the original feature merely because the branch name is the same.

96. How can criss-cross history affect merge-base selection?

Repeated cross-merges can produce more than one best common ancestor. Merge strategies may combine ancestors to construct a virtual base rather than use one obvious historical commit. This makes simplistic explanations based on a single remembered branch point unreliable.

I would inspect the graph and the actual merge-base results when a complex conflict seems surprising. A manually chosen older base may omit important relationships and worsen the merge. The practical goal is to understand both sides' intended changes and validate the result, not to assume that a clever graph operation removes the need for semantic review.

97. What is rerere, and what precautions does it need?

Rerere records conflict resolutions so Git can reuse them when a similar conflict occurs again. It can reduce repetitive work during rebases or repeated integrations. A reused textual resolution is not automatically correct for a changed surrounding context.

I would enable and use it according to the team's workflow, inspect reused resolutions and run relevant tests before completing the operation. Its cache is a convenience for the developer, not a shared code-review decision. If an earlier resolution was wrong, blindly reusing it can reproduce the mistake more efficiently.

98. How should binary-file conflicts be handled?

Binary formats often cannot be merged meaningfully as text, so the team needs a format-aware tool, a deliberate choice of version or a workflow that reduces concurrent edits. Attributes can select appropriate diff or merge behavior, but do not invent semantic merging for an opaque format. Preserve both sides while deciding.

For a design asset, I would involve the owner or use the supported application to combine changes, then verify the actual artifact. Choosing the newer timestamp is not a correctness rule. Locking or splitting assets may reduce future contention, while the recorded resolution should make clear which content was retained.

99. How does the ours merge strategy differ from the ours strategy option?

The ours merge strategy records a merge relationship while taking the current branch's tree as the result, effectively ignoring the other tree's content. The ours option to an appropriate normal merge strategy favors the current side for conflicting hunks while still incorporating nonconflicting changes. They have materially different effects.

I would inspect the exact command and explain the intended result before using either. A strategy that discards the other tree can make history say the branch was merged even though its content was not integrated. That may be useful in a specialized migration, but it is not a generic shortcut for resolving a difficult merge safely.

100. Why can large rename-heavy merges be expensive or confusing?

Rename detection has inexpensive matching steps and a potentially expensive fallback that compares remaining source and destination candidates. The rename limit bounds that exhaustive search; the similarity threshold decides how similar content must be to count as a rename. Raising a limit and lowering a threshold solve different problems, and neither tells Git what the author intended.

For a diagnostic diff, I would compare explicit similarity settings such as git diff -M90% and inspect whether the rename limit suppressed exhaustive detection. diff.renameLimit and the diff -l option control that limit; merge.renameLimit controls the corresponding merge setting, with strategy and version details checked in documentation. A larger limit may increase cost, while a lower similarity threshold may pair unrelated files. I would verify destination content and conflict resolutions in a disposable integration checkout before retaining any setting, rather than globally tuning Git to make one difficult merge look cleaner.

101. How do you make automated bisect results trustworthy?

Define the exit-code contract of the git bisect run wrapper explicitly: 0 classifies a revision as good, 1 through 127 except 125 classify it as bad, and 125 skips an untestable revision. Other exit codes abort the search. A missing command can return 127 and therefore be mistaken for a bad revision, so the wrapper must distinguish an infrastructure failure from the regression being investigated.

I would validate prerequisites and both known endpoints with the exact wrapper before starting. If an old revision cannot build for an unrelated compatibility reason, the wrapper can return 125; an invalid test environment should abort rather than assign an invented result. Skips near the transition can leave several possible first-bad commits instead of one proven culprit. Preserve the bisect log, resolve that ambiguity where possible and rerun the candidate and its predecessor under a stable environment before making a causal claim.

102. How do you resolve a submodule commit conflict?

The parent repository is choosing among submodule commit references, so inspect the submodule's own graph and content to determine the intended commit. The correct resolution may be an existing descendant or a new submodule merge commit. Then stage the chosen gitlink in the parent and ensure the referenced submodule commit is available to collaborators.

I would not replace the gitlink with an arbitrary local checkout simply to clear the conflict. Review and test both the submodule change and the parent integration. A parent commit pointing to an unpushed or inaccessible submodule commit can work locally while making every clean build fail.

103. How should stale worktree metadata be cleaned up?

Inspect git worktree list and the actual directories, then use the supported repair, move, remove or prune operation that matches the situation. Pruning administrative records is different from deleting a working directory containing edits. A temporarily unavailable external drive can make a valid worktree appear missing.

I would lock a worktree when its storage is intentionally intermittent and avoid treating absence as permission to discard it. Before removal, inspect uncommitted and untracked content and preserve anything valuable. Supported commands maintain relationships that a raw filesystem move or deletion can leave inconsistent.

104. How do refspecs control fetch and push scope?

A refspec maps source references to destination references, with syntax and options that determine which names are transferred or updated. Fetch and push apply them in different repository directions. Wildcards and force markers can broaden or alter the effect, so a remote name alone does not describe the operation's scope.

I would inspect configured refspecs when expected branches are missing or an operation touches more references than intended. Negative fetch refspecs can exclude selected sources under supported syntax. For a consequential update, use an explicit narrow mapping and verify the proposed source and destination rather than rely on an unfamiliar inherited configuration.

105. What does an atomic push guarantee?

When the server supports it, an atomic push updates all requested references together or rejects the update set, avoiding a partially updated group of refs. It does not make arbitrary external CI, deployment or notification effects part of the same transaction. Server support and policy still determine whether the request is accepted.

For a coordinated branch-and-tag update, I would consider atomic behavior when the workflow requires the references to move together. Validate the exact update set first and handle a rejection without assuming any reference changed. A successful atomic ref update still needs independent verification of downstream release or deployment outcomes.

106. How do server-side receive hooks differ from local hooks?

Receive hooks run on the receiving repository during push processing and can enforce policy over proposed reference updates. Local hooks run in the contributor's environment and may be missing or bypassed. Different receive hooks have different timing and transaction scope, which matters when enforcing multi-reference rules.

I would keep server-side checks deterministic and avoid expensive or unreliable external side effects inside a critical acceptance path where possible. A post-receive notification happens after accepted updates and cannot retroactively make the push atomic with another system. Policy should clearly distinguish rejection conditions from later automation failures.

107. Why is commit identity different from push authentication?

Author and committer metadata are fields in commit objects, while push authentication determines who is allowed to connect and update remote references. A user can push commits authored by someone else, and metadata alone does not prove account ownership. Signatures and hosting policies add separate verification layers.

I would diagnose a permission failure through the configured transport and credential mechanism rather than change user.name or user.email. Conversely, successful authentication does not guarantee the commits contain the intended attribution. Keep credentials out of repository URLs and logs where they could be exposed during routine inspection.

108. What is the purpose of safe.directory checks?

Git can refuse to trust a repository owned by a different user because repository-local configuration and related behavior can have security implications. safe.directory provides an explicit trust mechanism for appropriate cases. Broadly trusting every directory defeats the value of the check.

I would investigate why ownership differs, such as a container mount or shared build directory, and use the narrowest justified configuration or correct ownership through the approved environment setup. Do not paste a global wildcard exception merely to silence the error. The right fix depends on who controls the repository and how the process is expected to access it.

109. What should you consider before running code from an unfamiliar repository?

Cloning and reading a repository is different from executing its scripts, build tools or setup commands. Tracked files can contain arbitrary code, and configuration or tooling may invoke helpers under particular workflows. Inspect the source and use an appropriate isolated environment before execution when trust is uncertain.

I would avoid assuming that a familiar hosting domain makes every project safe. Hooks from a normal clone are not automatically installed as active local hooks, but a setup script can install them or perform other actions. Dependency installation, credential access and network permissions should match the actual task and source trust.

110. Why should CI report the exact commit or tree it tested?

A branch name can move while a job is queued or running, so the name alone does not identify the tested content. Record the exact source and, when relevant, generated merge commit used by the job. Approval and deployment should refer to the same intended revision under the workflow's rules.

I would check whether a pull-request job tested the branch tip, a merge with the target or another synthesized state. A green result for an earlier tip does not prove a later pushed commit passed. This is especially important when a target branch advances or conflict resolution changes the integration result after review.

111. How can a merge queue reduce integration failures?

A merge queue can validate proposed changes against an up-to-date integration state before accepting them in order, reducing races where individually passing branches fail together. The exact guarantees depend on the hosting implementation and test configuration. It is a collaboration mechanism built around Git history, not a core Git command.

I would ensure the queue tests the actual combination that will land and invalidates stale results when its inputs change. Long-running checks and frequent target updates affect throughput, so test design matters. A queue cannot compensate for missing tests or a deployment that later builds a different revision than the accepted one.

112. How do you connect a release tag to a deployed artifact reliably?

Record the exact commit and build inputs used to produce an artifact, then preserve verifiable provenance according to the release process. A tag names a source object, but does not by itself prove which dependencies, toolchain or generated content were used. Mutable tags or unpinned inputs weaken the relationship.

I would build from a clean identified revision, retain artifact digests and verify that deployment selects that artifact rather than rebuilding from a moving branch. Signed tags can support source identity, while artifact signing or attestations address later stages. The evidence should connect the full chain rather than stop at a release name.

113. What trade-offs matter when choosing a monorepo or multiple repositories?

A monorepo can simplify coordinated changes and shared history, while multiple repositories can provide independent ownership and lifecycle boundaries. Tooling, access control, build scale and dependency contracts determine the practical trade-offs. Repository count alone does not define whether the software is modular.

I would examine how often changes must be atomic across components, who needs access and how CI selects relevant work. A monorepo may need sparse workflows and scalable builds; multiple repositories may need versioned interfaces and coordinated releases. Moving files between repositories is an organizational and history decision that should preserve the evidence users actually need.

114. What does a sparse index optimize?

A sparse index can represent portions outside the sparse checkout more compactly, reducing index work for supported operations in large repositories. It is related to sparse checkout but changes index representation rather than merely hiding files. Tool compatibility and command behavior depend on the Git version and integration.

I would benchmark the actual developer workflow and verify that IDEs or scripts use supported Git interfaces instead of assuming a fully expanded index. A performance option is useful only if it preserves correct builds and review behavior. Document the required versions and fallback path rather than enable it globally without testing the affected tools.

115. Why should scripts avoid assuming every object ID has exactly 40 characters?

Git repositories can use different supported object formats, and abbreviated IDs also vary in length according to uniqueness and options. Hard-coded SHA-1-shaped parsing can fail in another repository or under a different output mode. Use documented Git commands and explicit formats to resolve objects instead of treating every hex string as the same kind of identifier.

I would validate a revision through Git and preserve full identifiers when durable identity matters. Object-format migration and interoperability require version and tooling checks; changing a regex is not a complete migration plan. Scripts should also distinguish object IDs from reference names and avoid accepting ambiguous input silently.

116. What problems can case-insensitive filesystems create for Git?

A repository can contain path distinctions that the local filesystem cannot represent independently, and case-only renames may need deliberate handling. Configuration reflects filesystem behavior but does not make an incompatible checkout magically safe. Cross-platform teams need a consistent path-naming policy.

I would use an intermediate temporary name for a case-only rename when required and verify the staged result. Test the repository on the relevant platform rather than assume a Linux checkout guarantees a macOS or Windows checkout works. Avoid introducing two tracked paths that differ only by case if supported contributors cannot check them out reliably.

117. How does Git represent executable bits and symbolic links?

Tree entries include limited mode information, such as a regular file's executable status or a symbolic-link entry. Git does not preserve every filesystem permission, owner or extended attribute. Checkout behavior for symlinks and executable bits also depends on platform capability and configuration.

I would inspect mode changes when a script works locally but fails in CI, and avoid treating a repository checkout as a full filesystem backup. A symlink's recorded target can point outside the checkout, so tools consuming untrusted repositories need appropriate path handling. Test deployment packaging rather than assume all filesystem semantics transfer unchanged.

118. What should you know before using git archive as a source package?

An archive exports a selected tree with archive-related attributes and options, rather than a full repository with history and working-tree extras. It generally does not include untracked build output, and submodule contents require separate handling. The chosen revision and export rules determine the package.

I would inspect the resulting archive and compare it with the build system's expected inputs. Attributes such as export-ignore can intentionally omit files, while generated metadata may differ from a checkout. A source archive can be useful for reproducible packaging, but only when dependencies, submodules and generated inputs are addressed explicitly.

119. How should parallel automation avoid corrupting a shared checkout's workflow?

Give independent tasks separate working trees and clear ownership of branches and repository-wide operations. Git's lock files protect specific updates, but do not make two agents editing the same index and files a coherent workflow. One task can otherwise stage, reset or commit another task's changes unintentionally.

I would inspect active operations before handling a lock error and never delete a lock file merely because a command is waiting. A stale lock can be removed only after establishing that no owning process is active and understanding the interrupted operation. Coordination and isolated checkouts prevent many errors that filesystem locking alone cannot solve.

120. How would you respond to an accidental destructive Git operation?

Stop additional cleanup, inspect the exact command and current state, and preserve available evidence before attempting recovery. Identify whether the lost work was committed, staged, stashed or never recorded, because each has different recovery options. Reflogs, existing references, other clones and backups may help, but no one command guarantees recovery.

I would first create references for any recovered commits and copy valuable current files to a safe location, then reconstruct the intended branch and validate its content. Avoid running aggressive garbage collection or repeated hard resets while experimenting. Report what was recovered and what remains uncertain, and address the workflow failure that allowed unrelated work to be discarded.

  1. Stop further destructive cleanup and record the exact operation.

  2. Preserve current files and identify recorded recovery candidates.

  3. Create explicit references to valuable recovered commits.

  4. Reconstruct the intended state and validate content.

  5. Report unrecovered work and improve the workflow boundary.

Git Documentation and Further Reading

These official Git resources provide command details and further study. Representative workflows were executed in isolated local repositories using Git 2.39.3 (Apple Git-146). No user project, hosted remote or production branch was changed by those tests. Hosting policies, remote authentication, LFS services, alternate object formats and large-scale performance were not exercised.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts