Git Topic
Git Interview Questions and Answers
Beginner Level Questions
1. What is Git and how does it differ from other version control systems?
Answer:
Git is a distributed version control system that tracks changes in source code during software development. Key differences from centralized VCS like SVN:
-
Distributed: Every developer has full copy of repository with complete history
-
Performance: Operations like commit, branch, merge are faster
-
Branching: Lightweight branching and merging
-
Offline Work: Can commit, branch, and view history without network connection
-
Data Integrity: Uses SHA-1 hashes to ensure data integrity
2. What is the difference between git pull and git fetch?
Answer:
-
git fetch: Downloads latest changes from remote repository but doesn't merge them. Your local working directory remains unchanged. -
git pull: Performsgit fetchfollowed bygit merge. It downloads and immediately integrates remote changes.
# Safe approach - review changes before merging
git fetch origin
git log HEAD..origin/main # See what would be merged
git merge origin/main
# Quick approach - directly update
git pull origin main
3. Explain the Git workflow: working directory, staging area, and repository.
Answer:
Git has three main areas:
-
Working Directory: Where you make actual changes to files
-
Staging Area (Index): Where you prepare changes for commit
-
Repository (.git directory): Where committed changes are permanently stored
# Workflow example:
echo "Hello" > file.txt # Working directory
git add file.txt # Staging area
git commit -m "Add file" # Repository
4. How do you create and switch to a new branch?
Answer:
# Create and switch in one command
git checkout -b feature-branch
# Equivalent separate commands
git branch feature-branch
git checkout feature-branch
# Modern Git (version 2.23+)
git switch -c feature-branch
5. What is a .gitignore file and why is it important?
Answer:
A .gitignore file specifies intentionally untracked files that Git should ignore. It's important because:
-
Prevents committing sensitive data (passwords, API keys)
-
Avoids tracking build artifacts and dependencies
-
Reduces repository size
-
Prevents OS-specific files from being committed
Example:
# Dependencies node_modules/ vendor/ # Environment variables .env .env.local # Build outputs dist/ build/ *.exe
Intermediate Level Questions
6. What is the difference between git merge and git rebase?
Answer:
-
git merge: Creates a new merge commit preserving the branch history. Safe for public branches. -
git rebase: Rewrites commit history by moving commits to new base. Creates linear history.
# Merge - preserves history
git checkout main
git merge feature-branch
# Rebase - linear history
git checkout feature-branch
git rebase main
When to use:
-
Use merge for public/shared branches
-
Use rebase for local/feature branches to keep history clean
7. How do you resolve a merge conflict?
Answer:
-
Identify conflicted files:
git status -
Edit files: Remove conflict markers (
<<<<<<<,=======,>>>>>>>) -
Mark as resolved:
git add filename -
Complete the operation:
git commit(merge) orgit rebase --continue
Example resolution:
# Before resolution
<<<<<<< HEAD
print("Hello from main")
=======
print("Hello from feature")
>>>>>>> feature-branch
# After resolution
print("Hello from main and feature")
8. What is git stash and when would you use it?
Answer:
git stash temporarily saves uncommitted changes so you can work on something else.
Common use cases:
-
Switching branches with uncommitted work
-
Pulling latest changes without committing
-
Saving work-in-progress temporarily
# Save changes
git stash
git stash save "WIP: feature implementation"
# List stashes
git stash list
# Apply last stash
git stash apply
# Apply and remove
git stash pop
# Clear all stashes
git stash clear
9. How do you amend the most recent commit?
Answer:
# Change commit message only
git commit --amend -m "New commit message"
# Add files to last commit
git add forgotten-file.txt
git commit --amend --no-edit
# Change both files and message
git add .
git commit --amend -m "Updated commit message"
Important: Don't amend commits that have been pushed to shared repositories.
10. What is the difference between git reset, git revert, and git checkout?
Answer:
-
git reset: Moves HEAD to specified commit (can be dangerous)-
--soft: Keep changes staged -
--mixed: Unstage changes (default) -
--hard: Discard all changes
-
-
git revert: Creates new commit that undoes changes (safe for shared history) -
git checkout: Switches branches or restores files
# Reset example
git reset --hard HEAD~1 # Completely remove last commit
# Revert example
git revert a1b2c3d # Safely undo specific commit
# Checkout example
git checkout -- file.txt # Discard file changes
Advanced Level Questions
11. What is Git cherry-pick and when would you use it?
Answer:
git cherry-pick applies specific commits from one branch to another.
Use cases:
-
Applying hotfix to multiple branches
-
Moving specific features between branches
-
Selective backporting of commits
# Apply specific commit to current branch
git cherry-pick a1b2c3d
# Apply range of commits
git cherry-pick start-commit^..end-commit
# Cherry-pick without auto-commit
git cherry-pick --no-commit a1b2c3d
12. Explain Git hooks and provide examples.
Answer:
Git hooks are scripts that run automatically before or after Git commands.
Common hooks:
-
pre-commit: Runs before commit (linting, tests) -
commit-msg: Validates commit message format -
pre-push: Runs before push (integration tests) -
post-receive: Runs after repository receives push (deployment)
Example pre-commit hook:
#!/bin/bash
# .git/hooks/pre-commit
# Run tests
npm test
if [ $? -ne 0 ]; then
echo "Tests failed! Commit aborted."
exit 1
fi
# Check for console.log statements
if git diff --cached --name-only | xargs grep -n "console.log"; then
echo "Found console.log statements!"
exit 1
fi
13. How do you find a bug introduced in the code using Git?
Answer:
Use git bisect for binary search through commit history.
# Start bisect session
git bisect start
git bisect bad HEAD # Current commit has bug
git bisect good v1.0.0 # This commit was good
# Test current commit, then mark
git bisect good # If current commit is good
git bisect bad # If current commit has bug
# Git will automatically narrow down to offending commit
git bisect reset # End bisect session
14. What is the difference between shallow clone and deep clone?
Answer:
-
Deep clone: Downloads complete history including all branches and tags
-
Shallow clone: Downloads limited history (only recent commits)
# Shallow clone - only last 10 commits
git clone --depth 10 https://github.com/user/repo.git
# Shallow clone specific branch
git clone --depth 1 --branch main https://github.com/user/repo.git
# Full clone (default)
git clone https://github.com/user/repo.git
Use shallow clones for: CI/CD pipelines, large repositories, when you only need recent history.
15. How do you rewrite commit history using interactive rebase?
Answer:
# Rebase last 5 commits
git rebase -i HEAD~5
# Common actions in interactive rebase:
# pick - use commit
# reword - use commit, but edit message
# edit - use commit, but stop for amending
# squash - combine with previous commit
# fixup - like squash, but discard message
# drop - remove commit
# Example to squash last 3 commits:
pick a1b2c3d Feature implementation
squash e4f5g6h Fix typo
squash f7g8h9i Add tests
Expert Level Questions
16. What are Git submodules and Git subtrees? When would you use each?
Answer:
Git Submodules:
-
References to external repositories
-
Maintains separate version control
-
Good for: Large dependencies, shared libraries
git submodule add https://github.com/user/lib.git
git submodule update --init --recursive
Git Subtrees:
-
Merges external repository into subdirectory
-
Single repository management
-
Good for: Vendor code, simpler dependency management
git subtree add --prefix=vendor/lib https://github.com/user/lib.git main
Choice depends on: Team workflow, dependency update frequency, repository size.
17. How does Git store data internally?
Answer:
Git uses content-addressable storage with four main object types:
-
Blobs: Store file contents
-
Trees: Represent directories (contain blobs and other trees)
-
Commits: Point to trees with metadata (author, message, parent)
-
Tags: Point to specific commits
# Explore Git objects git cat-file -p HEAD # Show commit contents git cat-file -p tree-hash # Show tree contents git cat-file -p blob-hash # Show file contents
All objects are stored in .git/objects/ and addressed by SHA-1 hash.
18. What is the reflog and how can it help recover lost commits?
Answer:
Reflog tracks all reference updates (branch switches, commits, resets, etc.).
# View reflog
git reflog
git reflog show --all
# Recover lost commit
git reflog
# Find commit hash before mistake
git reset --hard HEAD@{1}
# Recover deleted branch
git reflog | grep "deleted-branch"
git checkout -b recovered-branch a1b2c3d
Reflog expires after 90 days by default, so recover quickly!
19. How do you optimize a large Git repository?
Answer:
Optimization strategies:
# Clean up history git gc --aggressive # Garbage collection git repack -a -d --depth=250 --window=250 # Remove large files from history git filter-branch --tree-filter 'rm -f large-file.zip' HEAD # Or use BFG Repo-Cleaner # Use sparse checkout git sparse-checkout init git sparse-checkout set app/src # Shallow clone for CI git clone --depth 1 --no-single-branch https://repo.url
20. Explain Git's merge strategies and when to use them.
Answer:
Git has several merge strategies:
-
Recursive (default): Handles complex merges with multiple common ancestors
-
Octopus: Merges multiple branches simultaneously (for release automation)
-
Ours: Always uses our version, ignores theirs
-
Subtree: For merging repositories with different directory structures
# Specify merge strategy git merge -s recursive -X theirs feature-branch git merge -s octopus branch1 branch2 branch3 git merge -s ours legacy-branch # Conflict resolution options: -X ours # Prefer our changes -X theirs # Prefer their changes -X patience # Better diff algorithm for similar code
Strategy choice depends on: Branch complexity, conflict resolution preference, repository structure.
Bonus: Problem-Solving Questions
21. How would you handle a situation where you accidentally committed sensitive data?
Answer:
# 1. Remove from recent commit (if not pushed) git reset --soft HEAD~1 # Remove sensitive file, then recommit # 2. Remove from history (if pushed) # Use filter-branch or BFG Repo-Cleaner git filter-branch --force --index-filter \ 'git rm --cached --ignore-unmatch config/secret.txt' \ --prune-empty --tag-name-filter cat -- --all # 3. Force push and inform team git push origin --force --all # 4. Rotate all exposed secrets immediately!
22. Describe your Git workflow in a team environment.
Answer:
"I prefer a feature branch workflow:
-
mainbranch always deployable -
Create feature branches from
main:git checkout -b feature/description -
Regular commits with descriptive messages
-
Rebase feature branch before PR:
git rebase main -
Code review via pull requests
-
Squash merge into
main -
Delete feature branch after merge
-
Use semantic versioning with tags:
git tag v1.2.3
We also use:
-
Protected
mainbranch requiring PR reviews -
CI/CD pipelines running on PRs
-
Pre-commit hooks for code quality
-
Conventional commit messages"
These questions cover the essential Git knowledge needed for technical interviews, from basic concepts to advanced scenarios that demonstrate deep understanding of version control systems.
Comments (0)
No comments yet. Be the first to comment!