Toolmingo
Guides20 min read

50 Git Interview Questions (With Answers)

Top Git interview questions with clear answers and examples — covering branching, merging, rebasing, cherry-pick, reset, workflows, and advanced Git internals.

Git interviews test your understanding of distributed version control, branching strategies, conflict resolution, and day-to-day workflows. This guide covers the 50 most common questions — with concise answers and practical examples.

Quick reference

Topic Most asked questions
Basics init, clone, add, commit, status, log
Branching branch, checkout, merge, rebase
Remote fetch, pull, push, remote
Undoing changes reset, revert, restore, stash
Advanced cherry-pick, bisect, reflog, submodules
Internals objects, DAG, HEAD, refs
Workflows GitFlow, GitHub Flow, trunk-based

Basics

1. What is Git and how does it differ from other VCS tools?

Git is a distributed version control system (DVCS). Every developer has a full copy of the repository including complete history — unlike centralised systems (SVN, CVS) where history lives only on a central server.

Key differences:

Feature Git (DVCS) SVN (CVCS)
Repository Every clone is full Central server only
Offline work Full history available Limited
Branching Cheap (pointer to commit) Expensive (directory copy)
Speed Fast local operations Network-dependent
Data model Snapshots (DAG) Deltas

2. What are the three states in Git?

Every tracked file can be in one of three states:

Working Directory → Staging Area (Index) → Repository
      (modified)       (staged/added)       (committed)
  • Modified — file changed but not staged (git add moves it to staged)
  • Staged — file marked for the next commit (git commit moves it to repository)
  • Committed — data safely stored in the local repository

3. What does git init do?

Creates a new Git repository in the current directory by creating a .git/ folder containing:

.git/
├── HEAD          # points to current branch
├── config        # repository-level configuration
├── objects/      # all objects (blobs, trees, commits, tags)
└── refs/         # branch and tag references

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

# fetch: downloads remote changes, does NOT update working directory
git fetch origin
# Your local branch is unchanged; origin/main is updated

# pull = fetch + merge (or rebase with --rebase)
git pull origin main
# Downloads AND merges remote changes into your current branch

Use git fetch when you want to review changes before integrating. Use git pull when you're ready to integrate immediately.

5. What does git clone do?

Creates a local copy of a remote repository:

git clone https://github.com/user/repo.git
# Also: git clone git@github.com:user/repo.git  (SSH)
# Clone into a specific folder:
git clone https://github.com/user/repo.git my-folder
# Shallow clone (only latest commit):
git clone --depth 1 https://github.com/user/repo.git

git clone automatically sets up origin as the remote and checks out the default branch.


Branching and merging

6. What is a branch in Git?

A branch is a lightweight movable pointer to a commit. Creating a branch is nearly free (just writes a 41-byte file). The default branch is usually main or master.

git branch feature/login       # create branch
git checkout feature/login     # switch to branch
git checkout -b feature/login  # create + switch (shorthand)
git switch -c feature/login    # modern equivalent

7. What is the difference between git merge and git rebase?

Both integrate changes from one branch into another but produce different histories.

Merge — creates a new merge commit that ties the two histories together:

git checkout main
git merge feature/login
# Creates a merge commit with two parents
# Preserves complete history

Rebase — moves commits from one branch on top of another:

git checkout feature/login
git rebase main
# Rewrites feature commits on top of latest main
# Linear history, no merge commit
Merge Rebase
History Non-linear (merge commits) Linear
Preserves context Yes No (rewrites SHAs)
Safe for shared branches Yes No (never rebase public branches)
Use case Integrating completed features Keeping feature branch up-to-date

8. What is a fast-forward merge?

When the target branch has no new commits since the feature branch diverged, Git can simply move the pointer forward — no merge commit needed:

Before:  main → A → B
                      \
         feature        C → D

After FF: main → A → B → C → D
git merge feature          # fast-forward if possible
git merge --no-ff feature  # always create a merge commit
git merge --squash feature # squash all commits into one staged change

9. What is git rebase -i (interactive rebase)?

Interactive rebase lets you edit, reorder, squash, or drop commits before pushing:

git rebase -i HEAD~3    # rebase last 3 commits interactively

In the editor you can set each commit to:

Command Effect
pick Keep commit as-is
reword Keep commit, edit message
edit Pause to amend commit
squash Merge into previous commit (keep both messages)
fixup Merge into previous commit (discard this message)
drop Remove the commit entirely

Warning: Never rebase commits that have already been pushed to a shared branch.

10. What causes a merge conflict and how do you resolve it?

A conflict occurs when the same lines of a file are changed differently in two branches:

<<<<<<< HEAD
const greeting = "Hello";
=======
const greeting = "Hi there";
>>>>>>> feature/greeting

Resolution steps:

git merge feature/greeting    # conflict occurs
# 1. Open conflicted files, manually edit to desired state
# 2. Remove conflict markers (<<<<<<<, =======, >>>>>>>)
# 3. Stage the resolved files
git add src/greeting.js
# 4. Complete the merge
git commit

Use git mergetool to open a visual merge tool (e.g., VS Code, vimdiff).


Undoing changes

11. What is the difference between git reset, git revert, and git restore?

Command What it does Safe for shared branches?
git reset Moves HEAD (and branch pointer) backward No — rewrites history
git revert Creates a new commit that undoes a previous commit Yes — preserves history
git restore Discards changes in working directory / unstages files Yes (local only)
# Reset — move back 1 commit (keeps changes staged)
git reset --soft HEAD~1

# Reset — move back 1 commit (keeps changes in working dir)
git reset --mixed HEAD~1   # default

# Reset — discard ALL changes (dangerous!)
git reset --hard HEAD~1

# Revert — safe undo (creates a new "undo" commit)
git revert abc1234

# Restore — discard working directory changes
git restore file.txt

# Restore — unstage a file
git restore --staged file.txt

12. What are the three modes of git reset?

git reset --soft HEAD~1
# Moves HEAD back; changes stay STAGED (ready to recommit)

git reset --mixed HEAD~1   # default
# Moves HEAD back; changes go to WORKING DIRECTORY (unstaged)

git reset --hard HEAD~1
# Moves HEAD back; ALL changes DISCARDED — cannot easily recover

Memory aid: soft → staged, mixed → modified, hard → gone.

13. How do you recover a commit after git reset --hard?

Use git reflog — it records every position HEAD has been at:

git reflog
# abc1234 HEAD@{0}: reset: moving to HEAD~1
# def5678 HEAD@{1}: commit: add login feature  ← this is the lost commit

git reset --hard def5678   # recover it
# or create a new branch from it:
git branch recovered-branch def5678

reflog entries expire after 90 days by default.

14. What is git stash and when do you use it?

git stash temporarily saves uncommitted changes so you can switch branches without committing:

git stash                      # stash all tracked changes
git stash push -m "WIP login"  # stash with a message
git stash list                 # see all stashes
git stash pop                  # apply most recent stash and remove it
git stash apply stash@{1}      # apply specific stash (keep it)
git stash drop stash@{0}       # delete a stash
git stash branch fix/hotfix    # create a branch from a stash
git stash push --include-untracked  # also stash new files

15. How do you undo the last commit without losing changes?

# Keep changes staged:
git reset --soft HEAD~1

# Keep changes in working directory (unstaged):
git reset HEAD~1      # equivalent to --mixed

# Amend the last commit (change message or add files):
git add forgotten-file.js
git commit --amend --no-edit   # amend without changing message

Only amend commits that haven't been pushed to a remote.


Remote repositories

16. What is origin in Git?

origin is the default name Git gives to the remote repository you cloned from. It's just a convenient alias:

git remote -v                  # list remotes
git remote add upstream https://github.com/original/repo.git
git remote rename origin old-origin
git remote remove upstream
git fetch origin               # download from origin
git push origin main           # push local main to origin

17. What is the difference between git push and git push --force?

git push origin main
# Rejected if remote has commits not in local (non-fast-forward)

git push --force origin main
# OVERWRITES remote history — dangerous on shared branches

git push --force-with-lease origin main
# Safer: rejected if someone else pushed since your last fetch

Never force-push to main/master or any shared branch without team agreement.

18. What is a tracking branch?

A local branch that is linked to a remote branch:

git branch --set-upstream-to=origin/main main
# or when pushing for the first time:
git push -u origin feature/login
# -u sets the upstream tracking relationship

git status
# Shows "Your branch is up to date with 'origin/main'"
# Or "Your branch is 2 commits ahead of 'origin/main'"

git branch -vv   # show all tracking info

19. How do you delete a remote branch?

git push origin --delete feature/login
# or the older syntax:
git push origin :feature/login

To also delete the local branch:

git branch -d feature/login    # safe delete (prevents if unmerged)
git branch -D feature/login    # force delete

20. What does git remote prune origin do?

Removes stale remote-tracking references — local entries for remote branches that have been deleted:

git remote prune origin
# or fetch with pruning:
git fetch --prune
# or configure automatic pruning:
git config fetch.prune true

Cherry-pick, bisect, and advanced commands

21. What is git cherry-pick?

Applies the changes from one or more specific commits onto the current branch:

git cherry-pick abc1234               # apply one commit
git cherry-pick abc1234 def5678       # apply multiple commits
git cherry-pick abc1234..def5678      # apply a range (exclusive start)
git cherry-pick abc1234^..def5678     # apply a range (inclusive start)
git cherry-pick --no-commit abc1234   # apply changes without committing

Common use case: backporting a bug fix from main to a release branch.

22. How does git bisect work?

git bisect performs a binary search through commit history to find which commit introduced a bug:

git bisect start
git bisect bad                     # current commit is bad
git bisect good v1.2.0             # this tag/commit was good

# Git checks out the midpoint commit; test your code, then:
git bisect good    # or
git bisect bad

# Git keeps narrowing down until it finds the first bad commit
# When done:
git bisect reset   # return to original HEAD

Can also be automated with a test script:

git bisect run npm test

23. What is git tag and what are annotated vs lightweight tags?

Tags mark specific points in history (e.g., releases):

# Lightweight tag — just a pointer, no metadata
git tag v1.0.0

# Annotated tag — stores tagger info, message, and can be signed
git tag -a v1.0.0 -m "Release 1.0.0"

git push origin v1.0.0         # push a specific tag
git push origin --tags         # push all tags

git tag -d v1.0.0              # delete local tag
git push origin --delete v1.0.0  # delete remote tag

Prefer annotated tags for releases (they appear in git describe and carry metadata).

24. What is git reflog?

git reflog records every change to HEAD, including resets and checkouts that aren't in the regular commit log:

git reflog
# abc1234 HEAD@{0}: commit: fix login bug
# def5678 HEAD@{1}: checkout: moving from feature to main
# 789abcd HEAD@{2}: reset: moving to HEAD~1

# Recover a "lost" commit:
git checkout 789abcd
# or
git reset --hard 789abcd

Reflog is local only and not pushed to remotes.

25. What is git worktree?

Lets you check out multiple branches simultaneously in separate directories:

git worktree add ../hotfix hotfix/payment-bug
# Creates ../hotfix directory with hotfix branch checked out

git worktree list
git worktree remove ../hotfix

Useful when you need to work on a hotfix without stashing your current work.


Git internals

26. What are the four Git object types?

Git stores everything as four types of objects (identified by SHA-1 hash):

Object Description
blob File contents (no filename, no metadata)
tree Directory listing (maps names to blobs and other trees)
commit Snapshot pointer + metadata (author, message, parent SHA)
tag Annotated tag (points to a commit with extra metadata)
git cat-file -t abc1234   # show object type
git cat-file -p abc1234   # print object contents

27. What is the Git DAG?

Git history is a Directed Acyclic Graph (DAG) of commits. Each commit points to its parent(s):

  • Normal commits have one parent
  • Merge commits have two or more parents
  • The first commit has no parent

This structure enables Git's powerful branching and merging — branches are just named pointers (refs) into the DAG.

28. What is HEAD?

HEAD is a reference to the currently checked-out commit or branch:

cat .git/HEAD
# ref: refs/heads/main      → normal (attached HEAD)
# abc1234...                → detached HEAD (pointing to a commit directly)

Detached HEAD occurs when you check out a specific commit, tag, or remote branch directly:

git checkout abc1234    # enters detached HEAD state
# Any commits made here are not on any branch
# To keep them: git checkout -b new-branch

29. What is the difference between .gitignore and .gitkeep?

.gitignore — a file listing patterns for files/directories Git should ignore:

node_modules/
*.log
.env
dist/
.DS_Store

.gitkeep — a convention (not built into Git) — an empty file placed inside an otherwise empty directory to force Git to track the directory (Git doesn't track empty directories).

30. What is git gc?

git gc (garbage collection) cleans up unnecessary files and optimises the repository:

git gc
# Packs loose objects into pack files
# Removes unreachable objects older than 2 weeks
# Compresses the repository

git gc --aggressive    # more thorough but slower
git gc --auto          # only run if threshold is exceeded (run automatically)

Common workflow questions

31. What is GitFlow?

GitFlow is a branching model with long-lived branches:

main        — production-ready code only
develop     — integration branch
feature/*   — new features (branch from develop, merge back to develop)
release/*   — release preparation (branch from develop, merge to main+develop)
hotfix/*    — urgent production fixes (branch from main, merge to main+develop)

Good for: projects with scheduled releases. Overkill for: continuously deployed applications.

32. What is GitHub Flow?

A simpler workflow with one long-lived branch:

  1. Create a branch from main
  2. Add commits
  3. Open a pull request
  4. Review and discuss
  5. Deploy from the branch (optional)
  6. Merge to main

Good for: teams that deploy continuously.

33. What is trunk-based development?

All developers integrate to a single branch (trunk/main) at least once per day. Features are hidden with feature flags, not feature branches:

main ← everyone integrates here daily
       feature flags hide incomplete work

Benefits: eliminates long-lived branch merge pain. Requires: strong CI, feature flags, high test coverage.

34. What is a pull request (PR)?

A PR (GitHub/GitLab: MR) is a request to merge a branch into another. It provides a space for:

  • Code review and discussion
  • Automated CI checks
  • Documentation of the change

PRs should be small, focused, and reviewable — ideally under 400 lines of diff.

35. What is git commit --amend?

Modifies the most recent commit:

# Fix the commit message:
git commit --amend -m "fix: correct login validation"

# Add a forgotten file to the last commit:
git add forgotten.js
git commit --amend --no-edit

# Change author:
git commit --amend --author="Alice <alice@example.com>"

Only amend commits that have not been pushed to a remote.


Advanced questions

36. How do you squash multiple commits into one?

Option 1: Interactive rebase

git rebase -i HEAD~4    # rebase last 4 commits
# Mark all but the first as "squash" (or "fixup")
# Edit the combined commit message

Option 2: Merge with squash

git checkout main
git merge --squash feature/login
git commit -m "feat: add login feature"

37. What is a submodule?

A Git repository embedded inside another Git repository:

git submodule add https://github.com/lib/repo libs/repo
# Creates .gitmodules file

git clone --recurse-submodules https://github.com/user/main-repo
# Clone and initialise all submodules

git submodule update --remote    # update submodules to latest remote commit

Submodules track a specific commit, not a branch.

38. What is the difference between git diff and git diff --staged?

git diff              # changes in working directory vs staging area
git diff --staged     # changes in staging area vs last commit (what will be committed)
git diff HEAD         # changes in working directory vs last commit
git diff main feature # differences between two branches
git diff abc1234 def5678 # differences between two commits

39. How do you find which commit introduced a specific change?

# Search commit messages:
git log --grep="fix login" --oneline

# Search code changes (pickaxe):
git log -S "functionName" --oneline      # commit that added/removed the string
git log -G "regex.*pattern" --oneline    # commit where the string changed

# Who last changed each line:
git blame file.js
git blame -L 10,20 file.js    # only lines 10–20

# Combined with bisect for bug finding:
git bisect start
git bisect bad HEAD
git bisect good v1.0

40. How do you set up a Git hook?

Git hooks are scripts in .git/hooks/ that run at specific points:

# Pre-commit hook — runs before each commit
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
npm run lint || exit 1
EOF
chmod +x .git/hooks/pre-commit

Common hooks: pre-commit, commit-msg, pre-push, post-merge.

For team-wide hooks, use a tool like Husky (Node.js) or pre-commit (Python) that stores hooks in the repository.

41. What is git sparse-checkout?

Allows checking out only a subset of files in a large repository:

git clone --no-checkout https://github.com/user/mono-repo.git
cd mono-repo
git sparse-checkout init --cone
git sparse-checkout set packages/frontend packages/shared
git checkout main
# Only packages/frontend and packages/shared are downloaded

42. How do you rewrite history to remove a sensitive file?

If a secret was committed, rewrite history:

# Modern approach — git filter-repo (faster, recommended):
git filter-repo --path secrets.env --invert-paths

# Older approach — BFG Repo-Cleaner:
java -jar bfg.jar --delete-files secrets.env

# After rewriting, force-push ALL branches and rotate the secret immediately:
git push --force --all

This rewrites all affected commit SHAs — all collaborators must re-clone.

43. What is git archive?

Exports a snapshot of the repository as a zip or tar archive (without .git/):

git archive --format=zip --output=release.zip HEAD
git archive --format=tar.gz main:src/ > src.tar.gz

44. What does git log --oneline --graph --all show?

A compact ASCII visualisation of the entire commit graph:

git log --oneline --graph --all --decorate
# * abc1234 (HEAD -> main) fix: login bug
# | * def5678 (feature/login) feat: add 2FA
# |/
# * 789abcd initial commit

Useful aliases:

git config --global alias.lg "log --oneline --graph --all --decorate"

45. What is the difference between HEAD~1 and HEAD^1?

For most commits they are equivalent (the first parent), but they differ for merge commits:

Syntax Meaning
HEAD~1 First parent of HEAD
HEAD~2 First parent's first parent (grandparent)
HEAD^1 First parent of HEAD (same as ~1)
HEAD^2 Second parent of HEAD (merge parent — the branch that was merged in)
HEAD~2 vs HEAD^^ Both mean "grandparent via first parent"

Configuration and best practices

46. What are the three levels of Git configuration?

git config --system   # /etc/gitconfig — all users on the machine
git config --global   # ~/.gitconfig — current user
git config --local    # .git/config — current repository (highest priority)

# Common setup:
git config --global user.name "Alice"
git config --global user.email "alice@example.com"
git config --global core.editor "code --wait"
git config --global pull.rebase true          # rebase on pull
git config --global init.defaultBranch main
git config --global core.autocrlf input       # macOS/Linux
git config --global core.autocrlf true        # Windows

47. What is a .git/config vs .gitconfig file?

  • ~/.gitconfig — global config, applies to all repositories for the current user
  • .git/config — local config, applies only to the current repository (overrides global)

48. How do you write a good commit message?

Follow the Conventional Commits standard:

<type>(<scope>): <short summary>

<optional body — what and why, not how>

<optional footer — breaking changes, issue refs>

Types: feat, fix, refactor, docs, test, chore, perf, ci, build

feat(auth): add JWT refresh token rotation

Refresh tokens are now rotated on each use to limit exposure
window. Old tokens are invalidated immediately.

Closes #142
BREAKING CHANGE: /api/auth/refresh now returns a new refresh_token

Rules:

  • Subject line ≤ 72 characters
  • Use imperative mood ("add" not "added")
  • Body explains why, not what

49. What are some common Git mistakes to avoid?

Mistake Why it's bad Fix
Committing secrets/passwords Exposed even after deletion Remove with git filter-repo, rotate secret
Force-pushing to main Destroys teammates' history Use PR workflow; protect main branch
Giant commits Hard to review and bisect Commit small, focused changes
Merge without reviewing Introduces broken code Use PRs with required reviews
Ignoring .gitignore Commits build artifacts Set up .gitignore before first commit
Not pulling before pushing Leads to rejected pushes git fetch && git rebase regularly
Using git add . blindly Accidentally stages sensitive files Review with git diff --staged first
Rebasing shared branches Breaks history for everyone Only rebase private branches

50. What is the difference between SSH and HTTPS for Git remotes?

HTTPS SSH
URL format https://github.com/user/repo.git git@github.com:user/repo.git
Auth method Username + token (or credential manager) SSH key pair
Firewall Port 443 (usually allowed) Port 22 (sometimes blocked)
Setup Easier Requires key generation
Token expiry PATs expire Keys don't expire (unless configured)
# Generate SSH key:
ssh-keygen -t ed25519 -C "alice@example.com"
# Add public key to GitHub Settings → SSH Keys

# Convert existing remote from HTTPS to SSH:
git remote set-url origin git@github.com:user/repo.git

Common mistakes

Mistake Consequence Prevention
git reset --hard on committed work Permanent loss (unless in reflog) Use git revert on shared branches
Not using .gitignore node_modules in repo Create .gitignore before first commit
Squashing meaningful history Loses context Keep logical commits; squash only noise
Rebasing after pushing Broken teammates' repos Rule: never rebase public branches
Long-lived feature branches Painful merge conflicts Integrate to main at least daily
Empty commit messages Useless history Use Conventional Commits
Committing generated files Repo bloat Add dist/, build/ to .gitignore
Skipping PR reviews Quality regression Enforce branch protection rules

Git vs other VCS

Feature Git SVN Mercurial Perforce
Distribution Fully distributed Centralised Distributed Centralised
Branching cost Cheap (pointer) Expensive (copy) Cheap Moderate
Speed Very fast (local) Network-dependent Fast Network-dependent
Learning curve Steep Moderate Moderate Steep
Partial checkout Sparse checkout Yes (native) No Yes (mappings)
Large files git-lfs needed Good hg-largefiles Excellent
Industry use Dominant Legacy Niche VFX/AAA games

FAQ

Q: What is the difference between git pull --rebase and git pull? git pull fetches + merges (creates a merge commit). git pull --rebase fetches + rebases your local commits on top, keeping history linear. Set as default: git config --global pull.rebase true.

Q: How do I undo a git push? If no one else has pulled: git push --force-with-lease after resetting locally. If others have pulled: use git revert to create a new commit that undoes the changes — never force-push to shared branches.

Q: What is ORIG_HEAD? Git sets ORIG_HEAD before risky operations (merge, rebase, reset) so you can undo them: git reset --hard ORIG_HEAD.

Q: What is the difference between git stash pop and git stash apply? Both apply the stash to the working directory, but pop removes the stash from the stash list while apply keeps it. Use apply if you might need the stash again.

Q: How do you rename a branch?

git branch -m old-name new-name           # local rename
git push origin --delete old-name         # delete old remote branch
git push origin new-name                  # push new name
git push -u origin new-name               # set upstream tracking

Q: What is git log --follow? Tracks a file's history across renames: git log --follow -- src/utils/helpers.js. Without --follow, history stops at the rename point.

Related tools

Keep reading

All Toolmingotools are free & run in your browser

No sign-up, no upload, no watermark. Your files never leave your device.

Browse all tools