90+ Common Git Interview Questions With Clear Answers

September 20, 2025

Have you ever been asked to fix a merge conflict on the spot and felt your answers wobble? Git skills frequently appear in coding interviews, covering topics such as branching and merging, rebasing, commit history, pull requests, stash, and remote workflows. This guide on Git Interview Questions walks through real commands and clear scenarios so you feel fully prepared and confident in answering any Git-related question during an interview, securing the job or promotion you’re aiming for.

Interview Coder's AI Interview Assistant gives realistic mock questions, instant feedback, and hands-on practice focused on Git Interview Questions so you can build muscle memory and go into interviews calm and ready.

32 Basic Git Interview Questions and Answers

Blog image

1. What is a Git repository?

A Git repository stores a project’s files and the whole history of changes. You can have one locally in a folder or on a service like GitHub. Use commits to record snapshots, branches to try features, and commands like commit, push, and pull to share work.

2. How does Git work?

Git records snapshots of your project over time. You edit files in your working directory, stage chosen changes to the index, then commit a snapshot. Branches let you work in parallel, and merges or rebases combine work from different lines of development.

3. What is git add?

git add stages changes for the next commit. Example: git add file.txt stages that file. You can stage many files or parts of a file before committing the snapshot.

4. What is git push?

Git push uploads committed changes from your local branch to a remote like origin on GitHub. Example: git push origin main sends your local main branch to the remote main branch.

5. What is git status?

Git status shows which files are modified, which are staged, and which are untracked. Run it before committing to see what will go into the following snapshot.

6. What is a commit in Git?

A commit is a recorded snapshot of staged changes with a unique id and a message that explains why the change was made. Use git commit -m "message" to save your staged work.

7. What is branching in Git?

Branching creates a separate line of development so you can build features or fixes safely. Create a branch using either'git branch feature' or'git switch -c feature', and then commit your changes.

8. What is a conflict in Git?

A conflict occurs when different changes affect the same lines, or when a file is deleted in one branch and modified in another. Git stops the merge and marks the conflict inside the file, allowing you to edit it. Then, you can use Git add and commit to resolve the file.

9. What is merging in Git?

Merging brings changes from one branch into another and produces a merge commit if needed. Example: git merge feature while on main integrates feature into main, joining histories.

10. What is the difference between Git and GitHub?

Git is the version control system that runs on your machine and manages commits, branches, and history. GitHub is a cloud hosting service for Git repositories where teams push, open pull requests, and collaborate online.

11. What is the origin in Git?

Origin is the default alias for the remote repository you cloned. Use origin with commands like git fetch origin or git push origin main to refer to that remote.

12. What is the purpose of the .gitignore file?

.gitignore lists files and folders Git should ignore, such as logs, build artifacts, or local config. Add patterns like node_modules/ or *.log to prevent unwanted files from being tracked.

13. What is a version control system (VCS)?

A VCS tracks changes to files over time so you can review history, revert to past versions, and collaborate safely. Git is a distributed VCS where each developer has a full copy of the repository.

14. What is the git push command?

Git push updates a remote repository with commits from your local branch. It instructs the remote to accept your changes, allowing others to fetch or pull them.

15. What is the git pull command?

Git pull fetches commits from a remote and merges them into your current branch. It runs git fetch followed by git merge by default.

16. What does git clone do?

Git clone copies a remote repository, including files, branches, and complete history, to a new local folder—example: git clone https://github.com/user/repo.git clones that repo.

17. What are the advantages of using GIT?

Git supports parallel work with branches, gives fast local operations because each user has full history, works offline, and integrates with hosting services for collaboration.

18. What is the difference between git init and git clone?

git init creates a new empty Git repository in the current folder. git clone copies an existing remote repository, including its commits and branches, to your machine.

19. What is git add?

git add marks files or changes to include in the next commit. You can stage a file, multiple files, or use git add -p to stage parts of a file.

20. What is git status?

git status lists modified files, staged files, and untracked files. It helps you decide what to git add or commit next.

21. What is a commit in Git?

A commit records the staged snapshot and a message. Each commit has a hash id so you can reference, inspect, or revert that state later with commands like git log or git revert.

22. What is the purpose of the git clean command?

git clean deletes untracked files from the working directory. Use git clean -n to preview and git clean -f to delete; add -d to remove untracked directories.

23. What is a 'conflict' in git?

Conflicts occur when automatic merging cannot decide between two different changes. Open the conflicted file, choose the correct code, then git add and commit the resolution.

24. What is the meaning of 'Index' in GIT?

The Index, or staging area, holds the changes you choose to include in the next commit. You stage with git add and then create the commit from the index.

25. How do you change the last commit in git?

To modify the last commit, stage your new changes and run git commit --amend -m "new message". This replaces the previous commit on your current branch.

26. What is `git checkout`?

Git checkout can move you between branches or restore files to a previous state. Newer commands split this: git switch for branches and git restore for file changes.

27. How do you switch branches in Git?

Use git checkout branch-name or git switch branch-name to change branches. To create and switch in one step use git switch -c new-branch.

28. Name some popular Git hosting services?

Common services are GitHub, GitLab, Bitbucket, SourceForge, and Azure DevOps. These platforms host remotes, run CI, and support pull requests and issue tracking.

29. What are the different types of Git repositories?

A bare repository has no working directory and serves as a central remote for pushes and fetches. A non-bare repository includes a working directory where you edit files and commit changes.

30. How does Git handle file deletion?

Use git rm file.txt to remove a file from the working directory and stage its deletion. To stop tracking but keep the file locally, use git rm --cached file.txt.

31. How can you create an alias in Git?

Create shortcuts with git config --global alias. Check out so you can run' git co' instead of' git checkout'. Aliases live in your Git config and speed common workflows.

32. How do you rename a branch in Git?

Rename the current branch with git branch -m new-name. Rename another branch with git branch -m old-name new-name and then push or update remotes as needed.

Related Reading

35 Intermediate Git Interview Questions and Answers

Blog image

1. What is the difference between git fetch and git pull?

Git fetch downloads objects and updates remote tracking branches like origin/main without touching your current branch or working tree. Use it when you want to inspect upstream work, run tests, or stage a careful merge.

Example:

git fetch origin

git log HEAD..origin/main

Git pull is a convenience that runs git fetch, then integrates the fetched branch into your current branch. By default, it runs a merge.

Example: git pull origin main

Git Pull with Rebase

Prefer git pull --rebase when you want a linear history and want to replay your local commits on top of upstream:

Example: git pull --rebase origin main

Use git fetch when you need to review changes before merging. Use git pull for a quick sync when you trust the upstream branch and your changes are simple.

2. How do you revert a commit that has already been pushed and made public?

Use git revert to create a new commit that undoes a previous commit. This preserves shared history and avoids forcing collaborators to reconcile rewritten history.

Example:

git checkout main

git revert <commit-hash>

git push origin main

For a merge commit, specify the parent with -m: git revert -m 1 <merge-commit-hash>To revert several commits in one new commit:

git revert --no-commit <oldest-hash>^..HEAD

git commit -m "Revert range"

git push origin main

If you must rewrite public history, you need team agreement and a force push with a lease:

git reset --hard <target>

git push --force-with-lease origin main

3. What does git reset do?

Git reset moves HEAD and optionally updates the index and working tree. Modes:

  • --soft moves HEAD only. Staged and working files stay as is. Use to recombine commits before rewording or repacking.
    • git reset --soft HEAD~1
  • (default) mixed moves HEAD and updates the index, leaving the working tree modified. Use to unstage changes.
    • git reset HEAD~1
  • --hard moves HEAD and resets index and working tree to match the target. It discards uncommitted changes.
    • git reset --hard HEAD~1

Be careful with branches already pushed. If you reset public commits, you will need to force push and coordinate: git push --force-with-lease origin feature.

4. What is git stash?

Git stash saves the working tree and index so you can switch branches without committing WIP. Use it for quick context switches or to create a clean state for tests.Basic commands:

  • git stash push -m "WIP: refactor"
  • git stash list
  • git stash apply stash@{0}
  • git stash pop
  • git stash branch new-work stash@{0} # create branch and apply stash

Include untracked files with -u and ignored files with --all. Use stash for temporary work only; prefer small, focused commits when changes are meant to persist.

5. What is git reflog?

Git reflog records local movements of HEAD and other refs. It lets you recover commits lost by a reset, checkout, or branch delete.Common commands:

  • git reflog
  • git checkout HEAD@{5}
  • git branch recover HEAD@{5}

Reflog is local only and subject to expiration by garbage collection. Use it when you want to restore a state that no longer appears in git log.

6. How do you make an existing Git branch track a remote branch?

To set tracking, use either' git branch --set-upstream-to=origin/feature feature' or, when pushing for the first time, ' git push -u origin feature'. After this, git status shows ahead or behind counts, and git pull and git push use the tracked remote by default.

7. Can you explain heads in terms of git and also tell the number of heads that can be present in a repository?

HEAD is a reference that points to the tip commit of the checked-out branch or to a specific commit when detached. A repository can have many branch heads; there is no fixed limit.

Typical uses:

  • git checkout HEAD~1 # move to previous commit
  • git reset HEAD~3 # move HEAD back three commits

Branches are labels that point to commits. HEAD points at the current branch tip or at a commit object when you are not on a branch.

8. What is a conflict?

A conflict occurs when Git cannot automatically reconcile changes between branches. Common causes:

  • Both branches change the same line
  • One branch deletes a file, the other modifies

Git marks conflicts in files with conflict markers. Resolve steps:

Open the file and decide which changes to keep

Edit to remove markers

git add <file>

git commitTools:

  • git mergetool
  • git status shows conflicted files

Choose an approach that preserves intent: manual edit for semantic choices, merge driver for repeated patterns, or communicate with the author when necessary.

9. What is the functionality of git ls-tree?

git ls-tree shows the tree representation of a commit or tree object, including mode, type, SHA, and file name. Useful for plumbing, scripts, and verifying what a tree contains:

  • git ls-tree HEAD
  • git ls-tree -r --name-only HEAD # list files

Use it when you need a low-level view of a commit without checking out its contents.

10. What has to be run to squash multiple commits (last N) into a single commit?

Use interactive rebase to combine the last N commits: git rebase -i HEAD~N. In the editor, mark the top commit pick and the subsequent ones squash or fixup. After you resolve any conflicts, finish with: git rebase --continue. If the branch is published, push with care: git push --force-with-lease origin feature.

11. Can you tell something about git reflog?

Git reflog shows every local ref change, including checkouts, resets, and rebases. You can recover:

  • git reflog
  • git checkout -b rescue HEAD@{3}

Use reflog to locate a commit SHA even when it no longer appears in git log, then create a branch at that SHA to preserve it.

12. What consists of a commit object?

A commit object contains:

  • A tree reference that represents the snapshot of files
  • Zero or more parent commit references
  • Author and committer metadata with timestamps
  • The commit message
  • A SHA1 or SHA256 hash that identifies the commit

This structure makes commits immutable and allows Git to build a consistent history.

13. Explain the levels in git config and how you can configure values using them?

Git reads config in this order of precedence: system, global, local. Files:

  • System: /etc/gitconfig (use with --system)
  • Global: ~/.gitconfig or ~/.config/git/config (use with --global)
  • Local: .git/config in the repository (default or use --local)

Commands

  • git config --global user.name "Name"
  • git config --local core.ignorecase false
  • git config --list --show-origin # see values and sources

Values later in the chain override earlier ones. Use local configs for repo-specific behavior and global for user defaults.

14. What is a detached HEAD, and what causes this, and how to avoid this?

You have a detached HEAD when you check out a commit or tag rather than a branch:

  • git checkout <commit-hash>
  • git checkout tags/v1.0

Commits made in a detached state are not attached to a branch and can be lost. To avoid this, create a branch: git checkout -b feature-from-tagIf you have already made commits in a detached HEAD, create a branch pointing to them:git branch keep-me HEAD.

15. What does git annotate command do?

Git annotate is an older name for git blame. It shows which commit last changed each line of a file, who made the change, and when:

  • git blame -L 1,200 -- file.txt
  • git blame -e file.txt # show email addresses

Use this to find the commit that introduced a bug or to understand why a line exists.

16. What is the difference between git stash apply vs git stash pop commands?

Git stash apply applies a stash to the working tree but keeps it in the stash list: git stash apply stash@{0}. Git stash pop applies and removes the stash from the list: git stash pop. Use apply when you might reuse the same stash on multiple branches. Use pop when you want to apply and clear the saved state.

17. Why is it considered to be easy to work on Git?

Git makes parallel work easy with cheap branching and merging. Because it is distributed, you get a complete local repository with history, so many operations are fast and work offline. Pull requests and code review workflows integrate with CI and make collaboration explicit. Branches for features, hotfixes, and experiments let teams iterate without affecting main branches.

The staging area helps craft clean commits, and the history model supports powerful tools for recovery and refactoring.

18. How will you create a git repository?

To start local:

  • mkdir project
  • cd project
  • git init
  • git add .
  • git commit -m "Initial commit"

To copy an existing repository, use the following command: git clone git@github.com:org/repo.git. After creating a local repo, add a remote and push:

  • git remote add origin git@github.com:org/repo.git
  • git push -u origin main.

Use clone when you want the whole history of an existing project, and init when starting a new one.

19. Tell me something about git stash?

Use git stash push -m "message" to save WIP. Inspect with:

  • git stash list
  • git stash show -p stash@{0}

Recover to a new branch: git stash branch fixme stash@{0}. Use -u to include untracked files. Watch for conflicts when applying stash across branches, and prefer small commits for changes you intend to keep.

20. What is the command used to delete a branch?

Local delete:

  • git branch -d feature # safe, requires merged
  • git branch -D feature # force delete

Remote delete:git push origin --delete feature or git push origin: featureClean stale remote tracking branches: git remote prune origin. Use -d to protect work that is not merged, use -D when you know you want to remove it.

21. What differentiates between the commands git remote and git clone?

git clone creates a copy of a repository and sets its origin remote automatically:

  • git clone git@github.com:org/repo.git
  • git remote manages named remote URLs inside an existing repo:
  • git remote add upstream git@github.com:upstream/repo.git
  • git remote -v

Use git remote to add or rename remotes and to fetch from multiple sources. Use git clone to get a new repository copy.

22. What does git stash apply command do?

git stash apply restores a stash to your working tree but leaves the stash entry intact:git stash apply stash@{0}. If conflicts occur, resolve them and git add the files. To remove the stash after applying, run git stash drop.

23. Why do we not call git “pull request” as “push request”?

A pull request asks the target repository to pull changes into its branch. The request initiates a review and merge process, so the repository owner pulls the changes after approval. The name reflects the workflow: propose a branch for the maintainer to integrate rather than requesting that they accept a push directly.

24. What are the benefits of using a pull request in a project?

Pull requests centralize code review, automated checks, and discussion. They provide:

  • A place for reviewers to comment and request changes.
  • CI validation before merge.
  • A record of why and when changes occurred.
  • Options to squash or rebase before merge to keep history tidy

They help teams coordinate merges and enforce quality gates.

25. What is a Git bundle?

A git bundle packages repository objects and refs into a single file for transfer or archival:git bundle create repo.bundle --allYou can clone from a bundle using the command: git clone repo.bundle repo. Use git bundle verify repo.bundle to check contents. Bundles work well for air-gapped environments or shipping a repository snapshot.

26. What are the advantages of Git over SVN?

Key differences:

  • A distributed model gives every developer a full copy of the repository for speed and offline work.
  • Fast local operations reduce latency.
  • Lightweight branching and merging support many workflows.
  • The staging area allows granular commits.
  • Better tool support for code review and pull request workflows

These points explain why teams migrate to Git for modern development practices.

27. What is git stash?

Git stash saves uncommitted changes so you can switch context:

  • git stash push -m "WIP"
  • git stash list
  • git stash show -p stash@{0}
  • git stash pop
  • git stash drop stash@{0}
  • git stash clear

Use stash for temporary work and prefer commits for changes you plan to keep.

28. How do you revert a commit that has already been pushed and made public?

Steps:

  • git checkout main
  • git log # find the commit hash
  • git revert <commit-hash> # creates a new inverse commit
  • git push origin main

For merge commits, provide -m to choose a parent: git revert -m 1 <merge-hash>. If you need to revert several commits in one commit:

  • git revert --no-commit <oldest-hash>^..HEAD
  • git commit -m "Revert recent broken changes"
  • git push origin main

29. Explain the difference between reverting and resetting.

Git revert creates a new commit that undoes a previous commit without altering history. Use it on published branches. Git reset moves HEAD to another commit and can change the index and working tree. It rewrites history for commits that follow the target.

Using reset on public branches requires force pushing and team coordination. Use revert for safe public fixes, reset for local cleanup before publishing.

30. What is the difference between git reflog and log?

Git log shows the commit history reachable from a branch. It lists commits in the DAG. Git reflog records local ref movements like checkouts, resets, and rebases, even for commits no longer reachable by a branch. Use reflog to locate and recover commits whose log no longer shows.

31. What is the purpose of 'git tag -a'?

The git tag -a command creates an annotated tag, which stores useful metadata such as the tagger’s name, email, date, and a message:

Example:

git tag -a v1.0 -m "Release 1.0"

git push origin v1.0

Annotated tags are ideal for marking releases because they contain this extra information and can also be cryptographically signed with the -s option for added authenticity.

32. What is the difference between 'HEAD', 'working tree', and 'index' in Git?

HEAD is the current commit reference you have checked out. The working tree is the actual files in your directory. The index is the staging area that holds the following commit snapshot.

Typical commands:

  • git add <file> # move changes from working tree to index
  • git commit # write index to a new commit that HEAD points to
  • git checkout -- <file> # restore working tree from HEAD or index

33. How do you add a file to the staging area?

Stage a file:

  • git add path/to/file

Stage all changes:

  • git add

Stage interactively:

  • git add -p

Staging lets you craft commits that contain focused changes.

34. What is 'git diff?

The git diff command displays changes between the working tree and the index. Variants:

  • git diff # working tree vs index
  • git diff --staged # index vs last commit
  • git diff <commit> <commit> # compare two commits

Use git difftool to open a GUI diff or pass -U to change context lines.

35. What is the purpose of git cherry-pick?

The git cherry-pick applies a specific commit on top of your current branch: git cherry-pick <commit-hash>Options:

  • -x appends a reference to the original commit
  • -n applies changes without committing, so you can combine multiple picks

Use cherry pick for urgent fixes or to bring a single change across branches without merging the full branch. Handle conflicts as you would during a merge.

Related Reading

25 Advanced Git Interview Questions and Answers

Blog image

1. How do you manage multiple configurations for different projects in Git?

Use git config at the three scope levels to keep settings correct per environment and project:

  • System level: git config --system name value — applies to every user on the machine.
  • Global level: git config --global name value — applies to your user across repos.
  • Local level: git config name value — run inside a repo to set repo-specific values in .git/config.

For Scalable Setups

  • Use include and includeIf in your global ~/.gitconfig to conditionally bring in files based on path. Example: git config --global includeIf."gitdir:~/work/".path ~/.gitconfig-work. That way, all repos under ~/work get a separate identity, signing key, hooks path, or diff driver.
  • Use .git/config for repo-only settings such as remote URLs, core.hooksPath, or sparse checkout settings.
  • For CI or ephemeral environments, supply GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, GIT_COMMITTER_NAME, and GIT_COMMITTER_EMAIL as environment variables to override defaults without editing files.
  • Use conditional includes for Windows tooling differences and for GPG signing per repo.Troubleshooting tip: When identity or signing acts weird, run' git config --show-origin --list' to see which file set which key.

2. How do you handle large files with Git?

Use Git LFS to avoid polluting history with large binary blobs. Git LFS stores large objects outside normal packfiles and replaces them with pointer files in commits.

Basic Flow

  • git lfs install
  • git lfs track "*.bin" # adds patterns to .gitattributes
  • git add .gitattributes
  • git add bigfile.bin
  • git commit

Server Side

Choose a storage provider that supports LFS or host your own LFS endpoint. On GitHub and many hosts, LFS is supported with bandwidth and storage quotas.

Alternatives and Optimizations

  • Use Git Large File Storage for binaries and artifacts. For extensive histories, consider migrating with git filter-repo or the BFG cleaner to rewrite history and remove old, large files.
  • Use partial clone and shallow clone to reduce checkout size for clients: git clone --filter=blob:none, and then use git sparse-checkout to limit checked-out paths.

Edge Cases

LFS pointers in merge conflicts require a clean copy; avoid binary diffs that try to merge pointer files. For CI, use LFS fetch and checkout steps. If a legacy repo has packfile bloat, run git gc --aggressive and repack with pack-objects tuning.

3. What is the use of git submodule, and how do you update one?

The git submodule embeds a specific commit of an external repository inside your tree. Use it when you need a fixed snapshot of another repo rather than a shared history.

Common Commands

  • Add: git submodule add <url> path
  • Init for existing clones: git submodule init
  • Fetch submodules: git submodule update --init --recursive

To update a submodule to a newer commit:

  • Enter the submodule directory: cd path
  • Fetch and checkout the desired branch or commit:
    • git fetch origin
    • git checkout main
    • git pull

Back in the superproject, stage and commit the updated submodule reference:

  • git add path
  • git commit -m "Update submodule to latest main"

Automations

  • To update all submodules to the tip of their tracked branches: git submodule foreach 'git fetch && git checkout origin/$(git rev-parse --abbrev-ref HEAD) || true'

Caveats

  • Submodules record commits, not branches. For superproject automation, consider using a submodule—Recurse or scripting to keep refs in sync.
  • For nested or many submodules, prefer subtrees or a package manager where appropriate.
  • Troubleshoot: If a submodule shows as detached HEAD, update it to a branch and commit the new commit SHA in the superproject.

4. What is the significance of git push --force-with-lease over git push --force?

The git push --force replaces remote history without regard for remote updates and can silently overwrite others’ commits. git push --force-with-lease is a guarded overwrite: it verifies that the remote ref still points to the expected commit you last saw before allowing the update.

Mechanics

  • With --force-with-lease Git fetches the remote ref and compares it to your local reflog expected value, preventing the push if someone else pushed in the meantime.
  • You can use a specific lease: git push --force-with-lease=branch:expectedsha to make the check explicit.

Best Practices

  • Use it for private branches where you rebase locally, but not for shared branches like main.
  • Combine with protected branch rules on the server to disallow force pushes to critical branches.

Recovery Note

If a forced push breaks things, check the remote reflog on the server if available, or ask teammates to share SHAs; you can often recover via reflog or backups.

5. What command helps us know the list of branches merged to master?

Use git branch --merged master to list branches whose tips are reachable from master (i.e., merged). If you are on master, git branch --merged lists branches merged into the current branch.

To Filter and Clean

  • List merged local branches except master: git branch --merged master | egrep -v "(^\*|master|main|dev)"
  • Prune remote merged branches: First, use' git fetch -p'. Then, for each remote branch that is merged locally, consider using' git push origin --delete branch'.

Caveats

  • A branch can be considered merged even if it was cherry-picked; it checks commit reachability, not logical equivalence.
  • For remote branches, inspect git branch -r --merged origin/master.

Use git log --merges to inspect merge commits when you need to audit the merge history instead of reachability.

6. What is the best advisable step in cases of broken commits: Create an additional commit, or amend an existing commit?

Prefer creating a new commit for published commits. For local private commits, you can use git commit --amend or interactive rebase to fix content and messages.

Guidelines

  • If the commit is already pushed and shared, do not amend or rewrite published history. Create a corrective commit or use git revert to negate the bad changes and then commit the fix.
  • If the commit is local or on a branch used by only you, use git commit --amend for the last commit or git rebase -i to combine or edit older commits.

Risks

  • Amending rewrites history and changes commit shas. For shared branches, this forces others to resynchronize and can cause lost work if not coordinated.
  • Repeated amendments can obscure granular history and make bisecting more challenging. Keep a clean commit tree before pushing, but avoid rewriting after publishing.

7. How to revert a bad commit that is already pushed?

Two main safe approaches:

A. New Corrective Commit — Preferred

  • Edit files to remove or correct the incorrect changes.
  • git add files
  • git commit -m "Fix: revert bad behavior from commit <sha>"
  • git push

B. Use git revert to create an inverse commit that undoes a specific commit while preserving history:

  • git revert <bad-commit-sha>
  • Resolve conflicts if any, then git commit and git push

When Rewriting History is Permitted

  • If the branch is private and you can coordinate, use git reset --hard <good-sha> followed by git push --force-with-lease to rewrite the remote. Be careful. Always confirm no one else has based work on the bad commits.

Edge Cases

  • If multiple commits must be undone, revert them one by one or use a range with a strategy. When reverting a merge commit, prefer git revert -m 1 <merge-sha> and pick the parent to keep.
  • For large repositories or CI-exposed branches, prefer revert over history rewrite.

8. Explain the steps involved in removing a file from the git index without removing it from the local file system.

If a file is staged or tracked and you want to keep the file on disk but remove it from Git:

  • To unstage a staged file: git reset <file>
  • To remove tracking but keep the working copy: git rm --cached <file>
  • Add the file pattern to .gitignore to prevent future accidental adds:
    • echo "filename" >> .gitignore
    • git add .gitignore
    • git commit -m "Stop tracking filename"

Notes

  • The git rm without --cached deletes the file from the working tree as well. Use --cached to preserve the local copy.
  • If the file is already in history and you need it removed retroactively (to remove secrets or large files), use git filter-repo or the BFG tool to rewrite history, then coordinate a force push and inform collaborators.

9. What are the factors involved in considering which command to choose among: git merge and git rebase?

Both integrate commits from one branch into another, but with different outcomes.Merge:

  • Preserves original branch history and creates a merge commit.
  • Suitable for public branches and collaboration where historical context matters.
  • Safe and straightforward; does not rewrite commits.

Rebase

  • Reapplies commits onto a new base, producing a linear history and new commit SHAs.
  • Useful for cleaning up WIP commits and for small private feature branches before pushing.

Factors to Consider

  • Collaboration: Never rebase commits that others have based work on unless you coordinate.
  • Auditability: Merge commits preserve the topology and make it easy to see when a feature was integrated.
  • Bisecting: Rebasing rewrites SHAs, which can complicate tracing historical bugs if done after sharing.
  • Conflict frequency: Rebase forces you to resolve conflicts commit by commit, which can produce clearer conflict resolutions but is more work.
  • Team policy: Adopt a clear rule for when rebasing is allowed. For example, local developer branches may be rebased; the main branch should not.

Advanced Techniques

  • Use git rerere to reuse recorded resolutions when rebasing or merging repeatedly.
  • Use git pull --rebase to keep a clean feature branch when pulling remote updates.

10. How do you find a commit that broke something after a merge operation?

Use git bisect to binary search the commit history between a known good and a known bad revision:

  • git bisect start
  • git bisect bad # current broken commit
  • git bisect good <sha> # last known good commit

Git checks out a midpoint commit for testing. Mark it good or bad, and git bisect continues until it finds the first bad commit.

Automation

  • Use git bisect run <script> to automate tests. The script should exit 0 for good, 1 for bad, and 125 to skip.

Edge Cases

  • If history includes merges, bisect finds a single commit that introduced a regression; the commit might be a merge commit, and you may need to inspect the merge parents.
  • If a bug is non-deterministic or depends on external state, you may need to write a deterministic test harness for git bisect run.

Performance

  • For large repositories, use git bisect with shallow clones or specify a narrower range to reduce test iterations.

11. What are the functionalities of git reset --mixed and git merge --abort?

git reset --mixed <commit>:

  • Moves HEAD to <commit> and resets the index to match that commit, but leaves working files untouched. This unstages changes without discarding work.
  • Equivalent to git reset <commit> because --mixed is the default. Use when you want to change commit history or rearrange commits, but keep edits on disk.

git merge --abort:

  • Stops an in-progress merge and attempts to restore the pre-merge state. It runs only when a merge conflict occurs and when the merge sequence is recorded.
  • Internal behavior attempts to mimic the git reset --merge command, restoring the index and working tree to their pre-merge state.

When Merge --Abort Cannot Proceed

  • If you made manual changes that prevent restoring the state, it will fail. Use git reset --merge or manually reset files if needed.

Tip: Before aborting, stash local changes if you want to preserve partial conflict resolutions: git stash push -m "wip during merge."

12. How do you handle large files with Git?

(Expanded) Use Git LFS to replace large blobs in commits with small pointer files and store actual binaries in LFS storage. Benefits include smaller clone times and lighter packfiles.

Steps and Tips

  • Install: git lfs install
  • Track: git lfs track "*.psd" (this writes .gitattributes)
  • Commit .gitattributes and large files typically. CI must run git lfs fetch and git lfs checkout to restore binaries.
  • When migrating large existing files, use git filter-repo or the BFG tool to convert history, move binaries to LFS, and then force push a cleaned history.

Other Strategies

  • Use artifact storage for build outputs rather than committing them.
  • For monorepos, use sparse checkout and partial clone to reduce client payload.
  • Run git gc, repack, and tune pack settings for repository maintenance: git repack -ad && git gc --prune=now.

Be aware of host quotas and the requirement to authenticate LFS transfers in CI.

13. How do you squash multiple commits into one using Git rebase?

Interactive rebase is the usual path:

  • git rebase -i HEAD~N # N is the number of commits to squash
  • In the editor, change the first commit to pick and subsequent commits to squash or s.
  • Save and close. Git will combine the commits and open an editor to craft the mixed message.

Tips

  • If conflicts occur, resolve, git add files, then git rebase --continue.
  • For squashing public commits, coordinate because rebasing rewrites SHAs and requires force push with care: git push --force-with-lease.

Alternative

  • Use git reset --soft HEAD~N, then commit with a new message to form a single commit.

Edge Case

If you want to preserve some commit messages, use squash instead of fixup so you can edit the combined message before finalizing.

14. How do you reset a commit to a previous commit without losing changes in the working directory?

Use git reset --soft <commit-hash> to move HEAD to the target commit while leaving the index and working tree untouched. These stages change relative to the target. If you want the changes unstaged in the working directory: git reset --mixed <commit-hash>

To keep working on the tree while removing commits from history, use: git reset --soft HEAD~1. Then, edit and commit as needed.

Use caution: resetting published commits rewrites history and may require force pushing and coordinating with collaborators.

15. What is the difference between git reset hard and git clean -fd?

git reset --hard <commit>:

  • Resets HEAD, index, and working tree to <commit>. All staged and unstaged changes to tracked files are discarded. This rewrites the content on disk for tracked files.

git clean -fd:

  • Removes untracked files and directories from the working tree. It does not touch tracked files, the index, or commit history. Use -n or --dry-run to preview: git clean -nd.

Use Both Carefully

  • To fully restore the working tree to a clean commit: git reset --hard <commit> && git clean -fdx
  • For safety, always preview and back up uncommitted work or stash before destructive commands.

16. How do you apply a patch from a remote Git repository?

Approaches

A. Use git fetch and cherry-pick:

  • git fetch remote branch
  • git cherry-pick <sha>

B. Use git format-patch and git am:

  • On remote or in another clone: git format-patch -1 <sha> # creates patch file
  • On target repo: git am <0001-some.patch>

C. Use git apply for raw diff files:

  • curl http://server/patch.diff > patch.diff
  • git apply --index patch.diff # applies to working directory and stages

Notes

  • The git apply does not create commits; git am does.
  • For patches containing metadata and signoffs, prefer format-patch + am.
  • If patch touches binary files, git apply may fail; use format-patch/ git am to preserve binary attachments.

17. How do you configure a Git repository to use a specific user for a particular project?

Set per-repo configuration inside the repository:

  • git config user.name "Your Name"
  • git config user.email "your.email@example.com"

These write to .git/config. For commit signing:

  • git config user.signingKey <keyid>
  • git config commit.gpgsign true

For multiple projects use includeIf to auto apply different identities based on path or remote:

  • git config --global includeIf."gitdir:~/work/".path ~/.gitconfig-work

For automation use environment variables in CI:

  • GIT_AUTHOR_NAME
  • GIT_AUTHOR_EMAIL
  • GIT_COMMITTER_NAME
  • GIT_COMMITTER_EMAIL

18. What is a Git reflog, and how is it useful?

Reflog records updates to refs like HEAD and branch tips in your local repository. It logs resets, rebases, checkouts, merges, and more, even when those moves are not part of the commit history.

Use Cases

  • Recover deleted commits or branches: find the SHA in git reflog and git checkout -b recovered <sha>.
  • Inspect recent actions: git reflog show HEAD or git reflog <branch>.

Behavior Notes

  • Reflog is local only; it does not propagate to remotes.
  • Entries expire based on gc.reflogExpire and gc.reflogExpireUnreachable settings; adjust them if you need longer retention.
  • Reflog is the first tool for accidental resets or lost HEADs before trying more invasive recovery.

19. How do you manage multiple remotes in a Git repository?

Common Commands

  • Add remote: git remote add <name> <url>
  • List remotes: git remote -v
  • Fetch from a specific remote: git fetch <name>
  • Pull from specific remote branch: git pull <remote> <branch>
  • Push: git push <remote> <localref>:<remoteref>
  • Remove: git remote remove <name>

Advanced Patterns

  • Use multiple remotes for forks: Keep origin pointing to your fork and upstream to the canonical repo: git remote add upstream <url>.
  • Use different remotes for push and fetch with remote.<name>.pushurl and remote.<name>.url.
  • For distributed release workflows, use remotes for each CI or staging environment and push tags selectively: git push staging refs/tags/v1.2.3

Troubleshooting

  • If fetch/push seem to target wrong URLs, inspect .git/config or run git remote show <name>.

20. How do you configure and use Git hooks for pre-commit checks?

Hooks are scripts placed in .git/hooks. To run checks before commit:

  • Copy template: cp .git/hooks/pre-commit.sample .git/hooks/pre-commit or create .githooks and set core.hooksPath.
  • Make script executable: chmod +x .git/hooks/pre-commit
  • Script should inspect staged files using git diff --cached --name-only --diff-filter=ACM and run linters, tests, or formatters.

Example Detection and Fail Pattern

files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')

if [ -n "$files" ]; then

unfmt=$(gofmt -l $files)

if [ -n "$unfmt" ]; then

echo "Run gofmt on: $unfmt"

exit 1

fi

fi

To Share Hooks Across the Team

  • Store hooks in the repo and instruct developers to set core.hooksPath to that directory or use a tool like pre-commit framework, which installs hooks per repo.

Note: Server-side hooks on the Git server can enforce checks for branches even if clients bypass local hooks.

21. How do you perform a Git bisect to find the commit that introduced a bug?

Steps:

  • Start: git bisect start
  • Mark bad: git bisect bad
  • Mark good: git bisect good <sha>

Git checks out a middle commit. Test and mark it:

  • If bug present: git bisect bad
  • If bug absent: git bisect good

Repeat until bisect pinpoints the offending commit.

Automation

  • Use git bisect run ./test_script to run a test suite automatically—script exit codes control bisect progress.

Edge Cases

  • When the bug only reproduces under a specific environment, set up the test script to prepare that environment.
  • For flaky failures, use skip: git bisect skip <sha>

After finding the commit, git bisect reset returns you to the original HEAD. Inspect the identified commit and its parent to determine the fix.

22. How do you squash the last N commits into a single commit?

Option 1: Write Fresh Commit Message

  • git reset --soft HEAD~N && git commit

This moves HEAD back N commits while keeping changes staged, then creates a single new commit.Option 2: Combine Messages into an Editable Commit

  • git reset --soft HEAD~N && git commit --edit -m "$(git log --format=%B --reverse

HEAD@{N}..HEAD)"

This collects the original commit messages in chronological order and places them into the new commit message for editing.

Notes

  • After squashing, if the branch was pushed, use git push --force-with-lease and coordinate with teammates.
  • If you want to preserve author attributions, use git commit --author or reassign authors in the resulting commit.

23. What is Git bisect? How can you use it to determine the source of a (regression) bug?

Git bisect performs a binary search through commit history to locate which commit introduced a regression. Use a known bad commit and a known good commit to bound the search.

Procedure

  • Start: git bisect start
  • Mark endpoints: git bisect bad; git bisect good <good-sha>
  • Test each mid-commit and mark with git bisect bad or good
  • Optionally automate testing with git bisect run <script>

What It Does

Each step checks out a commit halfway between your good and bad points, reducing the search set by roughly half. It repeats until it finds the first commit that introduced the change.

Practical Advice

  • Make sure your tests for bisect are deterministic and isolated. If the bug depends on external services, create a reproducible harness.
  • After identifying the commit, inspect the diff and annotations with git show <sha> and git blame to plan the fix.

24. How do you configure a Git repository to run code sanity checking tools right before making commits, and prevent them if the test fails?

Sanity checks are quick tests that confirm the codebase is in a reasonable state before deeper testing. Use a precommit hook to run these checks.

Implementation Steps

  • Create .git/hooks/pre-commit or set core.hooksPath to a versioned hooks directory and add a precommit script.
  • Script should gather staged files: files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
  • Run quick linters, formatters, or smoke tests on those files. If any check fails exit with nonzero status to prevent commit.

Example Script Fragment

#!/bin/sh

files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')

[ -z "$files" ] && exit 0

unfmt=$(gofmt -l $files)

if [ -n "$unfmt" ]; then

echo "Run gofmt on: $unfmt"

exit 1

fi

exit 0

Shareability

Use the pre-commit framework or put hooks in a repo directory and have a small installer script run by developers. Server-side checks (push or pre-receive hooks) provide enforceable rules for teams.

Performance

Keep precommit checks fast. Longer tests belong to CI. Use staged file lists to limit scope.

25. How to recover a deleted branch using git reflog?

Steps to Recover

  • Inspect reflog to find the recent branch tip: git reflog show --all or git reflog
  • Locate the SHA where the branch existed or where the branch pointer moved. For example, you might see HEAD@{4}: checkout: moving from feature to master.
  • Create a branch at that SHA: git checkout -b preprod e2225bb.
  • Alternatively, use the following commands: git branch preprod e2225bb, then git checkout preprod.

Notes

  • Reflog entries expire per gc.reflogExpire, so act before expiry or increase retention: git config --local gc.reflogExpire 90 days.
  • If the branch was deleted remotely, you can often recover locally via reflog and then push it back: git push origin preprod.
  • If the needed SHA is not in your reflog but exists on another clone or CI, ask teammates or check server-side reflogs or backups.

Nail Coding Interviews with our AI Interview Assistant − Get Your Dream Job Today

Spending months grinding LeetCode, hoping to pass one tech interview? There's a smarter way. Interview Coder is your AI-powered, undetectable coding assistant for coding interviews, completely undetectable and invisible to screen sharing. While your classmates stress over thousands of practice problems, you'll have an AI interview assistant that solves coding challenges in real-time during your actual interviews.

Interview Prep Shortcut

Used by 87,000+ developers landing offers at FAANG, Big Tech, and top startups. Stop letting LeetCode anxiety kill your confidence. Join the thousands who've already taken the shortcut to their dream job.

Download Interview Coder and turn your following coding interview into a guaranteed win.


Interview Coder - AI Interview Assistant Logo

Ready to Pass Any SWE Interviews with 100% Undetectable AI?

Start Your Free Trial Today