Git interviews reward practical command fluency—logs, branches, merges, rebases, remotes, and conflict recovery on real repositories. If you are still building fundamentals, work through our Git & GitHub tutorial for beginners first. Below are 104 questions grouped by topic with clear explanations and concise strong-answer examples you can practise aloud.
Open each answer after you try the question yourself. For Java backend prep, see Java interview questions (part one).
git subcommand. Keep our Git command handy while you drill.
Interview context and how to prepare
What do Git interviews test in modern developer roles?
Git interviews usually test whether you can work safely in a team codebase.
Typical areas:
- Daily workflow — clone, branch, stage, commit, push, pull, and open pull requests
- History reading —
log,diff,status,show, and blame - Collaboration — merge vs rebase, conflict resolution, pull request hygiene
- Recovery — restore, reset, revert, stash, reflog, cherry-pick, and bisect
- Remote workflow — fetch, pull, push, tracking branches, tags
- CI integration — protected branches, required checks, hooks, signed commits
Most interviews are scenario-based.
Example:
“Your feature branch diverged from
main. What do you do?”
A strong answer explains the command and the reason:
“I would first fetch the latest remote state, inspect the branch difference, then either merge or rebase depending on team policy. I would avoid rewriting shared history unless the team explicitly allows it.”
A strong answer is:
Git interviews test whether I can collaborate safely: inspect history, create focused commits, work with branches and remotes, resolve conflicts, and recover from mistakes without damaging shared history.
What is a typical developer Git interview loop?
Git questions usually appear inside broader developer interviews, not always as a separate round.
| Interview area | Git focus |
|---|---|
| Phone / screen | Basic workflow: clone, branch, commit, push, pull |
| Technical round | Merge, rebase, conflicts, remotes, stash |
| Pairing / take-home | Feature branch workflow on a sample repo |
| Senior round | Trunk-based development, GitFlow, monorepos, protected branches, incident recovery |
Common prompts:
- “How do you undo a bad commit?”
- “How do you resolve a merge conflict?”
- “When would you use rebase instead of merge?”
- “How do you recover a commit that disappeared?”
- “How do you find which commit introduced a bug?”
A strong candidate does not only list commands. They explain safety:
“Before destructive commands, I check
git status, read the branch history, and make sure I am not rewriting commits already shared with the team.”
A strong answer is:
Git questions usually appear inside the technical or coding rounds. I expect basic workflow questions first, then scenarios around merge versus rebase, conflicts, undoing changes, remotes, and recovering lost work.
What is a realistic 3–5 week Git prep plan?
A realistic Git prep plan should include hands-on mistakes and recovery, not only command memorization.
| Week | Focus | Practice |
|---|---|---|
| 1 | Basics: status, add, commit, log, diff, branch, switch |
Create a repo and make 10 small commits |
| 2 | Collaboration: merge, rebase, conflict resolution, stash | Create two branches and resolve conflicts |
| 3 | Remotes: clone, fetch, pull, push, tracking branches, tags | Push to a remote and open a pull request |
| 4 | Recovery: restore, reset, revert, reflog, cherry-pick | Intentionally lose and recover a commit |
| 5 | Debugging and workflow: bisect, hooks, PR hygiene | Use git bisect on a small bug history |
Best practice drill:
Create a commit, reset it by mistake, then recover it using
git reflog. Our Git reflog recovery guide walks through that scenario step by step.
That gives real muscle memory for one of the most valuable Git recovery scenarios.
A strong answer is:
I would practise Git hands-on: normal commit and branch workflows first, then deliberately create conflicts and mistakes so I can demonstrate merge, rebase, reset, revert, reflog, and bisect rather than only define them.
What Git topics appear in modern developer interviews?
What interviewers are testing: Whether you know modern team practices—protected branches, signed commits, monorepos—without losing sight of safe daily collaboration.
Core Git skills have not changed much, but modern interviews often connect Git to team workflow and software supply chain practices.
Common topics:
- Trunk-based development and short-lived branches
- Pull request hygiene
- Protected branches and required CI checks
- Merge vs rebase policy
- Squash merge vs merge commit
- Signed commits in security-sensitive teams
- Monorepo workflows
- Sparse checkout and partial clone for large repositories
- Git LFS for large binary assets
The core bar remains the same:
- Keep history readable
- Avoid losing work
- Collaborate without breaking shared branches
- Recover safely when mistakes happen
- Explain trade-offs clearly
A strong answer is:
Modern Git interviews still test readable history and safe collaboration—I know branch protection and signed commits matter, but I lead with how I avoid losing work and breaking shared branches.
Git fundamentals and concepts
What is Git?
What interviewers are testing: Whether you understand Git's distributed model and can distinguish Git itself from hosting platforms such as GitHub.
Git is a distributed version control system used to track changes in source code and collaborate with other developers.
Important points:
- Git stores project history as commits.
- Each developer has a local repository with history.
- You can commit, branch, inspect history, and compare changes locally.
- Remote platforms such as GitHub, GitLab, and Bitbucket help teams collaborate.
- Git was created by Linus Torvalds for Linux kernel development.
A simple interview answer:
Git is a distributed version control system. It helps developers track code changes, work on branches, collaborate through remotes, and recover previous versions when needed.
A strong answer is:
Git is a distributed version control system. It helps developers track code changes, work on branches, collaborate through remotes, and recover previous versions when needed.
What is a repository in Git?
What interviewers are testing: Whether you can separate the working tree, staging area, and committed history from the .git metadata directory.
A Git repository is a project directory whose changes are tracked by Git.
It contains:
- Your working files
- Git history
- Branches and tags
- Configuration
- Metadata stored inside the
.gitdirectory
The .git directory is usually located at the root of the project. It stores Git’s internal database and metadata.
Important distinction:
| Term | Meaning |
|---|---|
| Working tree | Files you edit |
| Index / staging area | Changes prepared for commit |
| Repository | Committed history and Git metadata |
| Remote repository | Shared copy hosted elsewhere, such as GitHub or GitLab |
A strong answer is:
A repository is the tracked project plus Git metadata. The working tree contains files I edit, while the
.gitdirectory stores history, branches, and internal objects.
What are the main benefits of Git?
What interviewers are testing: Whether you can name practical Git benefits—local commits, branching, speed, and recovery—not just buzzwords.
Git is popular because it supports fast local work and team collaboration.
Main benefits:
| Benefit | Why it matters |
|---|---|
| Distributed workflow | Developers can commit and inspect history locally |
| Branching and merging | Teams can work on features safely |
| Speed | Most operations are local and fast |
| Data integrity | Git uses hashes to identify and verify objects |
| Collaboration | Works well with pull requests, reviews, and CI |
| Recovery | History, reflog, revert, and reset help recover from mistakes |
| Flexible workflows | Supports trunk-based, feature branch, release branch, and other models |
A practical interview answer:
Git is useful because it lets teams work independently, review changes, merge safely, and recover previous versions when something goes wrong.
A strong answer is:
Git is useful because it lets teams work independently, review changes, merge safely, and recover previous versions when something goes wrong.
What are the disadvantages of Git?
What interviewers are testing: Whether you recognize Git's real-world trade-offs: learning curve, binary files, history rewriting, and workflow discipline.
Git is powerful, but it has some practical challenges.
Common disadvantages:
- Learning curve — commands like rebase, reset, and reflog can confuse beginners.
- Large binary files — Git is not ideal for frequently changing large binaries unless Git LFS or another strategy is used.
- History rewriting risk — force push or incorrect rebase can disrupt shared branches.
- Merge conflicts — collaboration requires discipline around small changes and frequent sync.
- Repository size — very large repos may need sparse checkout, partial clone, or monorepo tooling.
- Workflow inconsistency — teams need agreed rules for branching, merge strategy, and commit style.
A strong answer is:
Git’s main challenge is not daily commit/push work; it is safe collaboration. Teams need clear workflow rules so rebasing, force pushing, and resolving conflicts do not break shared work.
What are the main differences between Git and SVN?
What interviewers are testing: Whether you compare Git and SVN by workflow model—distributed versus centralized—not only by vague performance claims.
Git and SVN are both version control systems, but their models are different.
| Area | Git | SVN |
|---|---|---|
| Model | Distributed | Centralized |
| Local commits | Yes | No, commits go to central server |
| Offline work | Strong local history and commits offline | Working-copy operations available, but commits and central history require server access |
| Branching | Local refs; lightweight and central to normal workflow | Repository paths/copies; commonly used in more centralized workflows |
| History | Full local history | Central repository history |
| Collaboration style | Pull requests, branches, distributed workflows | Centralized commit workflow |
| Large binaries | Needs Git LFS or special handling | Often simpler for large binary-heavy repos |
Important clarification:
Git can still be used with a central remote such as GitHub or GitLab, but each developer also has a local repository with full history in a normal clone.
A strong answer is:
The biggest difference is that Git is distributed while SVN is centralized. Git supports local commits and lightweight branching, while SVN relies more directly on a central server workflow.
Git is written in which language?
What interviewers are testing: Whether you know the factual implementation detail without overstating its interview importance.
Git is mainly written in C, with some supporting scripts and tooling historically written in shell, Perl, and other languages.
Interviewers rarely ask this in modern developer interviews, but the expected answer is simple:
“Git is mainly written in C.”
This question is usually factual. More practical interviews focus on daily workflow, recovery, branching, and collaboration.
A strong answer is:
“Git is mainly written in C.”
What is Git version control?
What interviewers are testing: Whether you explain version control as tracked history with commits, not merely file backup.
Git version control means tracking changes to files over time using commits.
It helps developers:
- See what changed
- See who changed it
- Understand why a change was made
- Compare versions
- Create branches for separate work
- Merge changes from different developers
- Roll back or revert bad changes
- Debug when a bug was introduced
A commit is like a snapshot of the project at a point in time, with metadata such as author, timestamp, and message.
A strong answer is:
Git version control records project history as commits, so a team can collaborate, review changes, recover older versions, and understand how the code evolved.
What are the three main steps of working with Git?
What interviewers are testing: Whether you understand the working tree, index, and repository as three distinct states in the commit workflow.
A simple Git workflow has three main areas:
- Working tree — files you edit.
- Staging area / index — changes selected for the next commit.
- Repository history — committed snapshots.
Typical flow:
Working tree → Staging area → Commit history
edit git add git commitExample:
git status
git add file.txt
git commit -m "Update file"Important terms:
| Area | Command example |
|---|---|
| Working tree | Edit files |
| Staging area | git add |
| Repository history | git commit |
A strong answer is:
I edit files in the working tree, stage the changes I want with
git add, and save them into history withgit commit.
Repository setup and configuration
How will you start Git for your project?
What interviewers are testing: Whether you can start version control in an existing project with git init, staging, and an initial commit.
To start using Git in an existing project directory, run:
git initThis creates a .git directory and starts tracking the project as a Git repository. For a fuller walkthrough, see what git init does and when to use it.
Typical first steps:
git status
git add .
git commit -m "Initial commit"A strong answer is:
I use
git initfor a new local repository, then stage files withgit addand save the first snapshot withgit commit.
What is git clone in Git?
What interviewers are testing: Whether you know what git clone copies locally and when shallow or partial clones intentionally fetch less data.
git clone creates a local copy of an existing remote repository.
Example:
git clone https://github.com/user/project.gitIt downloads:
- Project files
- Commit history
- Branch references
- Remote configuration, usually named
origin
Important point:
A normal clone creates a local repository with its own Git history and remote-tracking refs. Shallow or partial clone options can intentionally download less history or object data. See Git clone for SSH, --depth, and branch options.
A strong answer is:
git clonecopies an existing repository to my machine and sets up the remote connection so I can fetch, pull, and push changes.
How will you create a repository in Git?
What interviewers are testing: Whether you can choose between git init for a new repo and git clone for an existing remote project.
There are two common ways to create a Git repository.
For a new local project:
mkdir my-project
cd my-project
git initFor an existing remote project:
git clone <repository-url>After git init, Git creates a .git directory where it stores metadata, objects, refs, and configuration.
A strong answer is:
I create a new repository with
git init, or I usegit clonewhen the repository already exists on a remote server like GitHub or GitLab.
What are the different ways to start work in Git?
What interviewers are testing: Whether you know the two common entry paths—initialize locally or clone an existing remote repository.
You can start work in Git in two main ways:
| Situation | Command |
|---|---|
| Start version control in a new/local project | git init |
| Work on an existing remote repository | git clone <url> |
Use git init when the project is already on your machine and you want Git to track it.
Use git clone when the project already exists on GitHub, GitLab, Bitbucket, or another remote server.
A strong answer is:
I use
git initfor a new local repo andgit clonewhen I need a local copy of an existing remote repo.
What is the purpose of git config command?
What interviewers are testing: Whether you understand git config scopes and why identity settings matter for commit attribution.
git config is used to read and write Git configuration settings.
Common examples:
git config --global user.name "Deepak Prasad"
git config --global user.email "deepak@example.com"
git config --global init.defaultBranch mainConfiguration can be set at different levels:
| Level | Scope |
|---|---|
--system |
All users on the machine |
--global |
Current user |
--local |
Current repository |
For global username, email, and defaults, see Git config global settings.
A strong answer is:
git configcontrols Git settings such as username, email, default branch, editor, aliases, and repository-specific behavior.
How can we see the configuration settings of Git installation?
What interviewers are testing: Whether you can inspect effective Git configuration and trace a setting back to its source file.
Use this command to list Git configuration:
git config --listUseful variants:
git config --global --list
git config --local --list
git config user.name
git config user.emailIf you want to see where each setting comes from:
git config --list --show-originA strong answer is:
I use
git config --listto view current Git settings, and--show-originwhen I need to know which config file set a value.
How will you write a message with commit command in Git?
What interviewers are testing: Whether you write commit messages that explain intent, not only which files changed.
Use git commit -m to create a commit with a message.
git commit -m "Add login form validation"Good commit messages should explain the purpose of the change, not only the file edited.
Weak message:
git commit -m "changes"Better message:
git commit -m "Fix login validation for empty email"A strong answer is:
I use
git commit -mfor short commit messages, but for larger changes I write a clear subject and body explaining what changed and why.
How do we put a local repository on GitHub server?
What interviewers are testing: Whether you can connect an existing local repository to GitHub without unnecessary re-initialization.
To push a local repository to GitHub, first create an empty repository on GitHub (getting started with GitHub).
If the project is not already a Git repository, initialize and commit it first:
git init
git add .
git commit -m "Initial commit"Then connect the GitHub repository as a remote and push:
git remote add origin https://github.com/user/repo.git
git branch -M main
git push -u origin mainIf the project is already a local Git repository with commits, skip git init and the initial commit—add the remote and push instead.
Important points:
git remote add originconnects the local repo to the GitHub repo — see Git remote add examples.git push -u origin mainpushes the branch and sets upstream tracking.- After upstream is set, future pushes can usually use
git push.
A strong answer is:
I commit locally first, add the GitHub repo as a remote, then push my branch to GitHub with upstream tracking.
Commits, staging, and history
How can we see n most recent commits in Git?
What interviewers are testing: Whether you can limit git log output to recent history with practical formatting options.
Use git log with a number.
Example: show the 3 most recent commits:
git log -3Useful compact format:
git log --oneline -3A strong answer is:
I use
git log -norgit log --oneline -nto see the most recent commits quickly.
What is the meaning of stage in Git?
What interviewers are testing: Whether you understand staging as selecting changes for the next commit rather than saving immediately.
To stage means to select changes for the next commit.
Git has three common areas:
| Area | Meaning |
|---|---|
| Working tree | Files you are editing |
| Staging area / index | Changes selected for the next commit |
| Commit history | Saved snapshots |
Example:
git add login.js
git commit -m "Add login validation"Why staging is useful:
Suppose you changed two files, but only one change is ready. You can stage and commit only the finished file, while keeping the other file as work in progress. To unstage by mistake, see how to unstage files in Git.
A strong answer is:
Staging lets me choose exactly which changes go into the next commit, so I can keep commits focused and readable.
What is stored inside a commit object in Git?
What interviewers are testing: Whether you can describe what a commit object stores—tree, parents, author, committer, and message.
A Git commit object stores metadata about a snapshot of the project.
It includes:
- Tree reference, which points to the project snapshot
- Parent commit reference or references
- Author identity and date
- Committer identity and date
- Commit message
A commit is identified by a commit hash. In many repositories this is shown as a shortened hash such as:
a1b2c3dA strong answer is:
A commit stores a reference to the project snapshot, parent commit information, author/committer identity and dates, and commit message.
What is the use of git diff command in Git?
What interviewers are testing: Whether you know how to inspect unstaged, staged, and committed changes before making or reviewing a commit.
git diff shows changes between different Git states.
Common uses:
git diffShows unstaged changes in the working tree.
git diff --stagedShows staged changes that will go into the next commit.
git diff main feature-branchShows differences between two branches.
git diff <commit1> <commit2>Shows differences between two commits.
For staged, unstaged, and branch comparisons, see Git diff explained with examples.
A strong answer is:
I use
git diffto inspect exact line-level changes before staging, committing, reviewing, or comparing branches.
What is the use of git status command?
What interviewers are testing: Whether you use git status as a safety check before risky operations such as reset or rebase.
git status shows the current state of the working tree and staging area.
It tells you:
- Current branch
- Files changed but not staged
- Files staged for commit
- Untracked files
- Whether your branch is ahead, behind, or diverged from remote
Example:
git statusInterview use:
Before running risky commands such as reset, rebase, or checkout, check git status.
A strong answer is:
git statusis my first safety check. It tells me what changed, what is staged, what is untracked, and whether my branch is in sync with the remote.
What is the main difference between git diff and git status?
What interviewers are testing: Whether you know when a summary (status) is enough and when line-level detail (diff) is required.
git status gives a summary. git diff shows the actual content changes.
| Command | Shows |
|---|---|
git status |
Which files changed and their state |
git diff |
Exact line-by-line changes |
git diff --staged |
Exact staged changes |
Example:
Use git status to see that app.js changed.
Use git diff app.js to see what changed inside app.js.
A strong answer is:
git statustells me what changed at a file level.git difftells me exactly how the content changed.
What is the use of git rm command in Git?
What interviewers are testing: Whether you understand git rm versus untracking a file with --cached.
git rm removes a file from the working tree and stages the deletion. See Git rm for remove, undo, and --cached usage.
Example:
git rm old-file.txt
git commit -m "Remove old file"To remove a directory recursively:
git rm -r old-directoryIf you want to stop tracking a file but keep it locally, use:
git rm --cached config.localA strong answer is:
git rmremoves a tracked file and stages that deletion. I usegit rm --cachedwhen I want Git to stop tracking a file but keep it on disk.
Why do we use git log command?
What interviewers are testing: Whether you can use git log to investigate history by author, date, path, or branch.
git log shows commit history.
Common uses:
git log
git log --oneline
git log --author="Deepak"
git log --since="2 weeks ago"
git log -- path/to/fileIt helps you:
- Review project history
- Find when a change was made
- Search commits by author/date/file
- Understand branch history
- Prepare for debugging or release review
A strong answer is:
I use
git logto inspect committed history, understand what changed over time, and find commits related to a bug or feature.
Why do we need git add command in Git?
What interviewers are testing: Whether you understand why git add separates editing from committing and enables focused commits.
git add moves changes from the working tree to the staging area.
Example:
git add index.html
git commit -m "Update homepage layout"Why it matters:
- Lets you choose what goes into the next commit
- Helps create focused commits
- Allows partial staging
- Separates editing from committing
Useful command:
git add -pThis stages selected parts of a file interactively.
A strong answer is:
git addprepares changes for commit. It gives me control over what belongs in the next snapshot.
What is the difference between author and committer in Git?
What interviewers are testing: Whether you know that a commit records both who wrote the change and who created the commit object, and when those identities can differ.
Every commit stores two identities:
| Field | Meaning |
|---|---|
| Author | Who originally wrote the change |
| Committer | Who created the commit object in the repository |
They are usually the same person on a normal local commit.
They can differ when someone else applies the change, such as:
- Applying a patch with
git am - Cherry-picking or rebasing commits
- Maintainers committing work from another contributor
Example:
git log -1 --format='author: %an <%ae>%ncommitter: %cn <%ce>'A strong answer is:
The author wrote the change; the committer created the commit object. They match on ordinary commits but can differ after cherry-pick, rebase, or patch application.
How can we convert git log messages to a different format?
What interviewers are testing: Whether you can format git log output for reports or release notes using --pretty and --format.
Use git log --pretty or git log --format.
Examples:
git log --pretty=onelineCustom format:
git log --pretty=format:"%h - %an, %ar : %s"Example output:
ba72a6c - Dave Adams, 3 years ago : Update version numberUseful compact format:
git log --oneline --graph --decorateA strong answer is:
I use
git log --prettyor--formatwhen I need a custom history view for review, release notes, or debugging.
What is a commit message in Git?
What interviewers are testing: Whether you know what makes a commit message useful for future reviewers and release archaeology.
A commit message explains what changed and why.
A good commit message helps future developers understand project history.
Good commit messages are:
- Clear
- Specific
- Written in imperative style when possible
- Linked to ticket/issue ID if the team uses one
- Focused on the reason, not only the file name
Weak:
fixBetter:
Fix null user check in login flowSee how to write good Git commit messages for team-style examples.
A strong answer is:
A commit message should explain the intent of the change so future reviewers can understand the history without reading every line of diff.
How can we change a commit message in Git?
What interviewers are testing: Whether you understand that amending rewrites the commit and therefore becomes risky once that history has been shared.
To change the most recent commit message before pushing, use:
git commit --amend -m "New commit message"Important correction:
The command is --amend, not --ammend. Our Git commit amend guide covers safe use before and after push.
If the commit was already pushed, be careful. Amending rewrites commit history and creates a new commit hash.
For a shared branch, prefer team policy:
- Avoid rewriting shared history unless allowed.
- Use a new commit if safer.
- Coordinate before force pushing when the team allows history rewriting.
A strong answer is:
I use
git commit --amendfor an unpushed commit. If it is already pushed, I avoid rewriting shared history unless the team allows it.
How can you find the names of files that were changed in a specific commit?
What interviewers are testing: Whether you can list files touched by a specific commit using git show or related commands.
You can use git show with --name-only. See the Git show command guide for commit details, diffs, and file lists.
git show --name-only --pretty="" <commit>Another option:
git diff-tree --no-commit-id --name-only -r <commit>Example:
git show --name-only --pretty="" a1b2c3dA strong answer is:
I use
git show --name-onlyorgit diff-tree --name-onlyto list files changed in a specific commit.
How can we see differences between two commits in Git?
What interviewers are testing: Whether you can compare two commits or branches with git diff to review integration risk.
Use git diff with two commit hashes.
git diff <commit1> <commit2>Example:
git diff a1b2c3d e4f5g6hTo see only file names:
git diff --name-only <commit1> <commit2>To see a summary:
git diff --stat <commit1> <commit2>A strong answer is:
I use
git diff commit1 commit2for line-level changes,--name-onlyfor changed files, and--statfor a summary.
What are the different ways to identify a commit in Git?
What interviewers are testing: Whether you know multiple ways to reference a commit—hash, branch, tag, and relative refs like HEAD~1.
A commit can be identified in several ways.
Common ways:
| Identifier | Example |
|---|---|
| Full commit hash | a1b2c3d4... |
| Short hash | a1b2c3d |
| Branch name | main |
| Tag | v1.0.0 |
| Relative ref | HEAD~1 |
| Remote ref | origin/main |
| Special ref | HEAD, FETCH_HEAD, MERGE_HEAD |
Examples:
git show HEAD
git show HEAD~1
git show v1.0.0
git show origin/mainRelative refs like HEAD~1 are explained in our Git HEAD reference guide.
A strong answer is:
A commit can be referenced by hash, branch, tag, or relative refs like
HEAD~1. In daily work, short hashes and branch names are common.
What is git blame?
What interviewers are testing: Whether you use git blame for line history context without turning it into a personal attack.
git blame shows which commit last changed each line of a file. See git blame for syntax and practical usage.
Example:
git blame app.jsTo inspect a line range:
git blame -L 12,19 app.jsIt shows:
- Commit hash
- Author
- Timestamp
- Line content
Useful for:
- Finding when a line changed
- Understanding context before modifying code
- Locating the commit that introduced a behavior
- Asking the right teammate for background
Important interview note:
git blame should be used for context, not blaming people.
A strong answer is:
I use
git blameto understand the history of a line before changing it. It helps with context, but it should not be used to shame a developer.
Branching and pull requests
What are the common Git branching strategies, and when would you use each?
What interviewers are testing: Whether you can compare common branching models and explain which fits a team's release cadence.
There is no single branching strategy that fits every team.
Common Git branching strategies include:
| Strategy | How it works | Good for |
|---|---|---|
| Trunk-based development | Developers merge small changes into main frequently |
Fast-moving teams, CI/CD |
| Feature branch workflow | Each feature is developed in a separate branch and merged by pull request | Most product teams |
| GitFlow | Uses long-lived branches such as main, develop, release, and hotfix branches |
Release-heavy teams |
| Release branch workflow | main keeps moving, release branches stabilize production versions |
Products with multiple supported versions |
Modern teams often prefer short-lived feature branches with pull requests, CI checks, and protected main. Our Git workflow guide compares trunk-based, feature-branch, and GitFlow models in more detail.
A strong answer is:
I prefer short-lived feature branches or trunk-based development when CI is strong. GitFlow can still work for release-heavy products, but long-lived branches increase merge conflict risk.
What is the difference between HEAD and branch heads in Git?
What interviewers are testing: Whether you distinguish HEAD as the current checkout from the many branch refs that name commit tips.
In Git, HEAD usually refers to the current commit checked out in your working tree.
Important distinction:
HEADpoints to your current branch or commit.- Branch names are references that point to commits.
- A repository can have many branches, but your working tree has one current
HEAD.
Example:
git branch
git statusIf you switch from main to feature/login, HEAD now points to feature/login.
A strong answer is:
A repository can have many branch heads, but
HEADis the special reference for the current checkout.
Why do we create branches in Git?
What interviewers are testing: Whether you can justify branching for isolated work, review, and safer integration into mainline branches.
Branches let developers work on changes independently without disturbing the main code line.
Common reasons to create branches:
- Build a new feature
- Fix a bug
- Try an experiment
- Prepare a release
- Apply a hotfix
- Review code through a pull request
Example:
git switch -c feature/login-formBenefits:
- Keeps work isolated
- Makes code review easier
- Reduces risk to
main - Allows multiple tasks in parallel
- Supports CI checks before merge
A strong answer is:
I create branches to isolate work, keep commits focused, and merge only reviewed/tested changes into the main branch.
What are the different kinds of branches that can be created in Git?
What interviewers are testing: Whether you know that feature, release, and hotfix branch names are workflow conventions—not separate Git branch types.
Git does not technically distinguish feature, release, hotfix, or bugfix branches—they are ordinary refs. These names describe workflow conventions used by teams.
Common branch naming conventions include:
| Branch type | Purpose |
|---|---|
| Feature branch | Develop a new feature |
| Bugfix branch | Fix a normal bug |
| Hotfix branch | Fix an urgent production issue |
| Release branch | Stabilize code for release |
| Experiment branch | Test an idea without affecting main code |
| Main branch | Stable integration branch, commonly main |
Example names:
feature/login-form
bugfix/cart-total
hotfix/payment-timeout
release/v2.1A strong answer is:
Branch names should communicate purpose. Teams should also agree on branch lifetime and merge policy.
How will you create a new branch in Git?
What interviewers are testing: Whether you can create and switch branches with modern git switch syntax safely.
Use git switch -c to create and switch to a new branch.
git switch -c feature/login-formSee Git branch examples for creating and naming branches.
Older syntax also works:
git checkout -b feature/login-formTo create a branch without switching:
git branch feature/login-formA strong answer is:
I usually use
git switch -c branch-namebecause it creates the branch and moves me to it in one step.
How will you add a new feature to the main branch?
What interviewers are testing: Whether you can describe a feature-branch workflow with explicit remote/upstream updates before branching.
A safe workflow is:
- Create a feature branch from latest
main. - Make changes and commit them.
- Push the feature branch.
- Open a pull request.
- Run CI checks and request review.
- Resolve feedback and conflicts.
- Merge into
mainusing the team’s merge policy.
Update main according to the team's pull or rebase policy before creating the feature branch.
Example:
git switch main
git pull --ff-only origin main
git switch -c feature/login-form
# make changes
git add .
git commit -m "Add login form"
git push -u origin feature/login-formA strong answer is:
I do not directly push feature work to
main. I use a feature branch, pull request, CI checks, and review before merge.
What is a pull request in Git?
What interviewers are testing: Whether you understand pull requests as platform review workflows built on Git branches, not a core Git command.
A pull request is a collaboration workflow used on platforms such as GitHub, GitLab, and Bitbucket.
It lets developers:
- Compare a feature branch with a target branch
- Review code changes
- Discuss comments
- Run CI checks
- Request approval
- Merge the change safely
A pull request is not a core Git command. It is a platform feature built around Git branches and commits.
A strong answer is:
A pull request is a review and integration process around Git changes. It helps teams discuss, test, approve, and merge code safely.
What command will you use to delete a branch?
What interviewers are testing: Whether you can safely delete merged local and remote branches with the right commands.
To delete a local branch after it has been merged, use:
git branch -d feature/login-formThe -d option is safe because Git warns you if the branch has unmerged changes.
To delete a remote branch:
git push origin --delete feature/login-formA strong answer is:
I use
git branch -dfor a safely merged local branch andgit push origin --deletefor a remote branch.
What command will you use to delete a branch that has unmerged changes?
What interviewers are testing: Whether you understand -d versus -D and why force-deleting an unmerged branch is dangerous.
To force delete a local branch with unmerged changes, use:
git branch -D feature/old-workBe careful: this can remove branch work that is not merged elsewhere.
Before force deleting, check:
git log --oneline feature/old-work
git branch --contains feature/old-workA strong answer is:
I use
git branch -Donly when I am sure the branch work is no longer needed or is saved somewhere else.
Why is git push --force-with-lease safer than git push --force?
What interviewers are testing: Whether you know a safer way to update a rewritten remote branch without blindly overwriting a teammate's newer commits.
Both commands can replace remote branch history, but --force-with-lease checks that the remote ref still has the value Git expects before overwriting it. If another developer pushed new commits that you have not incorporated, the push is rejected instead of blindly replacing their work.
git push --force-with-lease origin feature/loginIt is commonly used after intentionally rebasing a private feature branch that has already been pushed. It is still history rewriting, so team policy matters. See Git push force examples for lease-based updates versus plain --force.
A strong answer is:
If I intentionally rewrite a pushed feature branch, I prefer
--force-with-leaseover--forcebecause it refuses to overwrite unexpected remote updates. It reduces the chance of deleting a teammate's work.
How will you switch from one branch to another in Git?
What interviewers are testing: Whether you switch branches safely after checking for uncommitted work or stashing it.
Use git switch to move between branches.
git switch main
git switch feature/login-formOur Git switch vs checkout guide covers modern branch switching and older checkout syntax.
Older syntax:
git checkout mainBefore switching, check whether you have uncommitted changes:
git statusIf your work is unfinished, commit it, stash it, or move it before switching branches.
A strong answer is:
I use
git switch branch-nameand checkgit statusfirst so I do not accidentally carry uncommitted changes into another branch.
How can we see the last commit on each branch in Git?
What interviewers are testing: Whether you can inspect the latest commit on each branch with git branch -v or related commands.
Use:
git branch -vThis shows local branches and the latest commit on each branch. See how to list Git branches for local, remote, and merged views.
To include remote branches:
git branch -avExample output:
feature/login 83b576c Add login form
* main 7b96605 Merge pull request #42
testing 972ac34 Add test dataA strong answer is:
I use
git branch -vto see each local branch with its latest commit, andgit branch -avwhen I also want remote branches.
Merge, rebase, and conflict resolution
How can we know if a branch is already merged into main in Git?
What interviewers are testing: Whether you can verify whether a branch's commits are already contained in another branch.
To list branches already merged into the current branch:
git branch --mergedTo check branches merged into main:
git branch --merged mainTo list branches not yet merged:
git branch --no-merged mainRemote variants:
git branch -r --merged origin/main
git branch -a --merged mainA strong answer is:
I use
git branch --merged mainbefore deleting a branch, and--no-mergedto find branches that still contain unmerged work.
What is a merge conflict in Git?
What interviewers are testing: Whether you understand why merge conflicts occur when Git cannot auto-merge competing changes.
A merge conflict happens when Git cannot automatically combine changes from two branches.
Common causes:
- Same lines changed differently in both branches
- One branch deletes a file while another edits it
- Same file renamed differently
- Large formatting changes mixed with logic changes
Example:
<<<<<<< HEAD
const label = "Save";
=======
const label = "Submit";
>>>>>>> feature/button-copyA strong answer is:
A merge conflict means Git needs human help to decide the final content. I resolve it by understanding both changes, editing the file, staging it, and completing the merge.
How can we resolve a merge conflict in Git?
What interviewers are testing: Whether you can resolve conflicts by editing markers, staging fixes, and completing the merge.
A safe conflict resolution process is:
- Run
git statusto see conflicted files. - Open each conflicted file.
- Remove conflict markers.
- Keep the correct final content.
- Run tests if needed.
- Stage resolved files.
- Continue the merge or rebase.
For a merge conflict:
git status
# edit files
git add conflicted-file.js
git commitFor a rebase conflict:
git status
# edit files
git add conflicted-file.js
git rebase --continueTo abort:
git merge --abort
git rebase --abortOur Git merge conflict resolution guide walks through fast-forward merges, manual fixes, and aborting safely.
A strong answer is:
I resolve conflicts by understanding intent, not by blindly choosing one side. After editing, I stage the file and continue the merge or rebase.
What is the alternative command to merging in Git?
What interviewers are testing: Whether you know rebase as the main alternative integration strategy and when teams prefer it.
The common alternative to merging is rebasing.
git rebase mainMerge and rebase both integrate changes, but they affect history differently.
| Command | Effect |
|---|---|
git merge |
Combines histories and may create a merge commit |
git rebase |
Replays commits on top of a new base for linear history |
See Git merge vs rebase for when teams choose each approach.
A strong answer is:
The alternative to merge is rebase. Merge preserves branch history, while rebase creates a cleaner linear history by replaying commits.
What is rebasing in Git?
What interviewers are testing: Whether you can explain rebase as replaying commits and when it rewrites history.
Rebasing means moving or replaying commits from one base commit to another.
Example:
git switch feature/login
git rebase mainThis takes commits from feature/login and reapplies them on top of the latest main. For command syntax and conflict handling, see Git rebase explained with examples.
Benefits:
- Cleaner linear history
- Easier commit review
- Avoids unnecessary merge commits in feature branches
Risks:
- Rewrites commit hashes
- Can confuse collaborators if done on shared branches
- Conflicts may need to be resolved during the rebase
A strong answer is:
Rebase is useful for cleaning up local feature branch history, but I avoid rebasing shared public branches unless the team explicitly allows it.
What is the golden rule of rebasing in Git?
What interviewers are testing: Whether you know not to rebase commits that others may already have based work on.
The golden rule is:
Do not rebase commits that other people may already be using.
Rebase rewrites commit history and creates new commit hashes. If others have based work on the old commits, rebasing can create confusion and duplicate-looking history.
Safe use cases:
- Rebase your local feature branch before opening a pull request
- Clean up commits before pushing
- Rebase private branches that only you use
Risky use cases:
- Rebasing
main - Rebasing a shared release branch
- Rebasing a branch other teammates are actively using
A strong answer is:
I rebase private work, not shared history. If a branch is public and used by others, I prefer merge or coordinate carefully.
Why do we use interactive rebasing in Git?
What interviewers are testing: Whether you understand interactive rebase for cleaning up local commit history before review.
Interactive rebase lets you edit commit history before sharing or merging a branch.
Common uses:
- Squash multiple small commits
- Reword commit messages
- Reorder commits
- Drop accidental commits
- Split a large commit
- Clean up noisy local history
Example:
git rebase -i HEAD~3In the editor, you can use actions such as:
pick
reword
edit
squash
fixup
dropA strong answer is:
I use interactive rebase to clean up my private feature branch before review. I avoid using it on shared history.
What is the command for rebasing in Git?
What interviewers are testing: Whether you know the basic rebase commands and how to continue or abort after conflicts.
Basic command:
git rebase mainTypical workflow:
git switch feature/login
git fetch origin
git rebase origin/mainInteractive rebase:
git rebase -i HEAD~3Continue after resolving conflicts:
git rebase --continueAbort a rebase:
git rebase --abortA strong answer is:
I use
git rebase <base-branch>to replay my branch on top of another branch, andgit rebase -iwhen I need to clean up local commits.
What are ours and theirs merge options in Git?
What interviewers are testing: Whether you understand -X ours / -X theirs as per-hunk merge preferences—not whole-branch replacement—and how rebase can invert the meaning.
During a normal merge, -X ours favors the current side when Git encounters conflicting hunks, while -X theirs favors the other side. Non-conflicting changes from both branches are still merged.
Example:
git merge -X ours feature/login
git merge -X theirs feature/loginDo not confuse -X ours with the ours merge strategy, which ignores the other tree's content entirely.
During rebase, the meaning of "ours" and "theirs" can be counterintuitive because Git is replaying commits onto the new base.
A strong answer is:
During a normal merge,
-X oursor-X theirsinfluences automatic resolution of conflicting hunks; it does not mean "replace the whole branch with this side." I use these options cautiously.
How can we ignore merge conflicts due to whitespace in Git?
What interviewers are testing: Whether you know whitespace-related merge strategy options and their risks.
Use a merge strategy option that ignores whitespace changes.
Example:
git merge -X ignore-space-change feature/formattingOther useful option:
git merge -X ignore-all-space feature/formattingThis is useful when one branch has formatting-only whitespace changes and another branch has logic changes.
Important caution:
Ignoring whitespace can be risky in languages or files where whitespace is meaningful.
A strong answer is:
I can use
-X ignore-space-changeduring merge, but I still review the result because whitespace can be meaningful in some files.
Stash, cherry-pick, and recovery
What is the purpose of git stash drop?
What interviewers are testing: Whether you understand that git stash drop permanently removes a stash entry.
git stash drop removes a stash entry.
List stashes:
git stash listDrop the latest stash:
git stash dropDrop a specific stash:
git stash drop stash@{2}Be careful: dropping a stash deletes that saved work from the stash list.
A strong answer is:
I use
git stash dropwhen I no longer need a saved stash. I checkgit stash listfirst so I do not drop the wrong one.
What is git stash?
What interviewers are testing: Whether you use stash to park unfinished work without creating a premature commit.
git stash temporarily saves uncommitted changes and gives you a clean working tree. See Git stash explained with examples for apply, pop, and list workflows.
Use it when:
- You need to switch branches quickly
- You are interrupted by an urgent bug
- Your current work is not ready to commit
- You want to pull or rebase with a clean working tree
Example:
git stash push -m "WIP login form"List stashes:
git stash listA strong answer is:
git stashis for temporary work-in-progress. I use it when I need a clean working tree but do not want to commit unfinished changes.
What is the command to apply a stash?
What interviewers are testing: Whether you know the difference between git stash apply and git stash pop.
To apply the latest stash:
git stash applyTo apply a specific stash:
git stash apply stash@{1}Difference between apply and pop:
| Command | Behavior |
|---|---|
git stash apply |
Applies stash but keeps it in stash list |
git stash pop |
Applies stash and removes it from stash list if successful |
A strong answer is:
I use
git stash applywhen I want to keep the stash, andgit stash popwhen I want to apply and remove it.
Why do we use git reset command?
What interviewers are testing: Whether you understand the difference between moving a ref and changing the index/working tree, particularly the destructive effect of --hard.
git reset moves HEAD and can also change the staging area and working tree depending on the mode.
Common modes:
| Command | What it does |
|---|---|
git reset --soft HEAD~1 |
Undo commit, keep changes staged |
git reset --mixed HEAD~1 |
Undo commit, keep changes unstaged |
git reset --hard HEAD~1 |
Undo commit and discard changes |
git reset file.js |
Unstage a file (legacy style) |
git restore --staged file.js |
Unstage a file (modern, clearer intent) |
Default reset mode is --mixed. Our Git reset examples compare soft, mixed, and hard modes.
git reset remains important for moving refs and changing the index, while git restore --staged is often clearer when your only intention is to unstage a file.
Important warning:
git reset --hardcan permanently discard uncommitted changes.
A strong answer is:
I use
git resetto move branch history or unstage changes. I avoid--hardunless I am sure I do not need the local changes.
How can we revert a commit that was pushed earlier and is public now?
What interviewers are testing: Whether you choose git revert for shared history instead of rewriting public commits.
Use git revert.
Example:
git revert <commit>git revert creates a new commit that undoes the changes from the selected commit. See Git revert for shared-branch safety.
This is safer for public/shared branches because it does not rewrite history.
Do not use git reset on a public branch unless your team has explicitly agreed to rewrite history.
A strong answer is:
For a pushed public commit, I use
git revertbecause it preserves shared history and creates a new undo commit.
In Git, how will you compress last n commits into a single commit?
What interviewers are testing: Whether you can squash local commits with interactive rebase without rewriting shared branches.
Use interactive rebase. Our how to squash commits in Git guide shows squash and fixup workflows.
Example: squash the last 3 commits:
git rebase -i HEAD~3In the editor, keep the first commit as pick and change the later commits to squash or fixup.
Example:
pick a1b2c3d Add login form
squash d4e5f6g Fix validation typo
squash h7i8j9k Update button textImportant warning:
Squashing rewrites commit history. Do this on local/private branches, not shared public branches unless the team allows it.
A strong answer is:
I use interactive rebase to squash local commits before review. I avoid squashing commits that other developers already depend on.
How can we clean unwanted files from our working directory in Git?
What interviewers are testing: Whether you use git clean carefully with preview flags before deleting untracked files.
Use git clean to remove untracked files from the working tree.
Preview what will be removed:
git clean -nRemove untracked files:
git clean -fRemove untracked directories too:
git clean -fdRemove ignored files also:
git clean -fdxImportant warning:
git clean can permanently delete untracked files. Always run git clean -n first — see Git clean for safe preview flags.
A strong answer is:
I use
git clean -nto preview, thengit clean -for-fdonly when I am sure the untracked files can be removed.
What is cherry-pick in Git?
What interviewers are testing: Whether you understand cherry-pick as applying one commit's changes onto the current branch.
git cherry-pick applies the changes from an existing commit onto the current branch. See Git cherry-pick examples for backport workflows.
Example:
git switch release/v1.0
git cherry-pick a1b2c3dCommon use cases:
- Backport a bug fix to a release branch
- Apply one commit without merging the full branch
- Move a small fix from one branch to another
Important points:
- Your working tree should be clean before cherry-picking.
- Conflicts may occur and must be resolved.
- Cherry-pick creates a new commit with a different hash.
- It should not replace normal merging for full feature branches.
A strong answer is:
I use cherry-pick when I need one specific commit from another branch, such as backporting a production fix without merging unrelated work.
Remotes, push, and pull
What does git pull do internally?
What interviewers are testing: Whether you know that pull combines fetching with integration and can explain why some teams prefer explicit fetch + merge/rebase.
git pull updates the current branch with changes from a remote branch.
git pull first fetches from the remote, then integrates the fetched branch into the current branch. In current Git, when no reconciliation method is configured, a pull is fast-forward-only and fails if the histories have diverged. You can explicitly choose rebase with --rebase or merge with --no-rebase; configuration can also set the preferred behavior.
git fetch— downloads objects and updates remote-tracking refs.- Integration — fast-forward, rebase, merge, or squash according to options/configuration.
See Git fetch vs pull for when to fetch without merging.
Equivalent commands:
git fetch origin
git merge origin/mainOr with rebase:
git pull --rebaseOur Git pull --rebase guide explains when teams prefer rebase over merge on pull.
A strong answer is:
git pullfetches first and then integrates the upstream branch. Current Git defaults to fast-forward-only when no reconciliation method is configured; teams can explicitly configure or request merge, rebase, or squash behavior.
What does git push do internally?
What interviewers are testing: Whether you understand when a push is rejected because the remote ref cannot fast-forward—not merely because the remote has any newer commits.
git push uploads local commits to a remote repository and updates the matching remote branch or ref. See Git push explained with examples for upstream, rejection, and error handling.
Example:
git push origin mainThis sends commits from local main to origin/main if the remote can accept the update.
Important correction:
git push does not do fetch + merge. That describes git pull, not git push.
A push may be rejected if:
- Updating the target branch would require a non-fast-forward update because its current tip is not an ancestor of the commit you are pushing
- Branch protection blocks direct push
- Required CI checks failed
- You do not have permission
- Signed commits are required but missing
A strong answer is:
git pushsends objects needed by the remote and requests ref updates. A normal push is rejected when updating the target branch would not be a fast-forward or when server policy blocks it.
What is the main difference between git clone and git remote?
What interviewers are testing: Whether you distinguish cloning a repository from managing remotes in an existing local repo.
git clone and git remote are related but used for different purposes.
| Command | Purpose |
|---|---|
git clone |
Creates a new local copy of an existing repository |
git remote |
Manages remote connections in an existing repository |
Example clone:
git clone https://github.com/user/project.gitExample remote add:
git remote add origin https://github.com/user/project.gitWhen you clone a repository, Git usually creates a remote named origin automatically.
A strong answer is:
git clonecreates a new local repository from a remote.git remotemanages remote URLs after a repository already exists.
How can we rename a Git remote such as origin?
What interviewers are testing: Whether you can rename or update remote URLs with git remote subcommands.
Use git remote rename.
git remote rename old-name new-nameExample:
git remote rename origin upstreamTo verify:
git remote -vA strong answer is:
I use
git remote renameto change the local nickname of a remote. It does not rename the actual repository on GitHub or GitLab.
Is origin a special branch in Git?
What interviewers are testing: Whether you know origin is a remote nickname, not a special branch.
No. origin is not a branch.
origin is the default name Git gives to the remote repository when you run git clone.
Example:
git remote -vYou may see:
origin https://github.com/user/project.git (fetch)
origin https://github.com/user/project.git (push)Remote-tracking branches look like:
origin/main
origin/feature-loginImportant distinction:
| Name | Meaning |
|---|---|
origin |
Remote repository nickname |
main |
Local branch |
origin/main |
Remote-tracking branch |
A strong answer is:
originis the default remote name, not a branch.origin/mainis a remote-tracking branch.
How can we configure Git to not ask for password every time?
What interviewers are testing: Whether you can configure authentication without storing plain-text passwords—using SSH or an OS-appropriate credential helper.
Use a credential helper, SSH key, or platform-specific authentication tool.
Common options:
git config --global credential.helper cacheThis caches credentials temporarily in memory.
Configure the credential helper provided by your OS or Git installation—for example Git Credential Manager where installed—or use SSH keys.
For GitHub and similar platforms, use:
- Personal access token for HTTPS
- SSH key authentication
- GitHub CLI or credential manager
Important:
Do not store plain-text passwords in scripts or repository files.
A strong answer is:
I use SSH keys or a credential manager so Git can authenticate securely without asking for credentials on every push.
What are the major protocols used by Git for data transfer?
What interviewers are testing: Whether you can name Git's common transport protocols and when each is used in practice.
Git can transfer data using several protocols.
Common protocols:
| Protocol | Example |
|---|---|
| Local | /path/to/repo.git |
| HTTPS | https://github.com/user/repo.git |
| SSH | git@github.com:user/repo.git |
| Git protocol | git://server/repo.git |
In modern hosted workflows, HTTPS and SSH are the most common.
A strong answer is:
Git supports local, HTTPS, SSH, and Git protocol URLs. In daily work, I mostly use HTTPS with a token/credential manager or SSH keys.
What is the git:// protocol in Git?
What interviewers are testing: Whether you understand the unauthenticated git:// transport and why HTTPS or SSH is preferred for team repositories.
The git:// protocol is a native Git transfer protocol that usually runs on port 9418.
It was designed for fast transfer, but the protocol itself has no authentication built into that transport.
Because of that, modern teams usually prefer:
- HTTPS
- SSH
- Hosted Git platforms with access control
A strong answer is:
The
git://protocol is an unauthenticated transport; HTTPS and SSH are more common for real team repositories.
How can we work on a project where we do not have push access?
What interviewers are testing: Whether you can describe a fork-and-pull-request workflow when you lack push access to upstream.
If you do not have push access, use a fork-based workflow.
Important correction:
There is no standard git fork command. Forking is usually a feature of platforms such as GitHub, GitLab, or Bitbucket.
Typical flow:
- Fork the repository on the hosting platform.
- Clone your fork.
- Create a feature branch.
- Push to your fork.
- Open a pull request to the original repository.
Example:
git clone https://github.com/your-user/project.git
cd project
git remote add upstream https://github.com/original/project.git
git switch -c fix/readmeA strong answer is:
If I do not have push access, I fork the repository, push changes to my fork, and open a pull request to the upstream project.
Hooks, security, and automation
What are Git hooks?
What interviewers are testing: Whether you understand client-side and server-side hooks and what problems they solve.
Git hooks are scripts that run automatically when certain Git events happen.
Examples:
| Hook | Runs when |
|---|---|
pre-commit |
Before a commit is created |
commit-msg |
After commit message is written, before commit completes |
pre-push |
Before pushing |
pre-receive |
On server before accepting pushed refs |
post-receive |
On server after accepting pushed refs |
Common uses:
- Run formatters
- Run lint checks
- Validate commit messages
- Block secrets from being committed
- Enforce server-side policies
- Trigger notifications or deployment steps
A strong answer is:
Git hooks automate checks around commits and pushes. Local hooks help developers catch issues early, while server-side hooks enforce team-wide rules.
What programming languages can Git hooks be written in?
What interviewers are testing: Whether you know hooks are executable scripts and can be written in any language available on the system.
Git hooks can be written in any language that can run as an executable script on the machine.
Common choices:
- Shell script
- Python
- Perl
- Ruby
- Node.js
- PowerShell
The hook must be runnable by Git in the target environment and placed in the configured hooks path. On Unix-like systems, script hooks normally also need the executable bit set.
Example on Linux:
chmod +x .git/hooks/pre-commitA strong answer is:
Hooks are executable scripts. They are often shell scripts, but they can be written in Python, Node.js, Perl, or any language available in the environment.
How does Git protect repository integrity?
What interviewers are testing: Whether you distinguish Git's content-integrity mechanisms from authentication, authorization, encryption, and signed provenance.
Git uses object hashes so object names are tied to their contents, which provides strong integrity checking and makes accidental corruption detectable.
Important clarifications:
- Git does not encrypt your source code by default. Hashing is not encryption.
- Hashes alone do not authenticate who created a commit or prove that a ref has not been intentionally rewritten; signatures and trusted hosting/access controls address those concerns.
- Git is also transitioning from SHA-1 toward SHA-256 repository formats; official Git documentation describes SHA-256 as the chosen successor.
Repository security also depends on:
- Access control on the Git server
- SSH keys or token-based authentication
- Branch protection rules
- Required reviews and CI checks
- Signed commits or tags where provenance matters
- Secret scanning and dependency scanning
A strong answer is:
Git uses content hashes to identify objects and detect inconsistent or corrupted content. Authentication and provenance are separate concerns handled with access controls and, where required, signed commits or tags.
How can we set up a Git repository to run code sanity checks before a commit?
What interviewers are testing: Whether you can use pre-commit hooks for fast local checks while relying on CI for heavier validation.
Use a pre-commit hook for fast local checks.
Common checks:
- Formatting
- Linting
- Secret scanning
- Basic unit tests
- Commit size checks
Example flow:
Developer runs git commit
→ pre-commit hook runs checks
→ commit succeeds only if checks passFor heavier tests such as integration tests, UAT, browser tests, or deployment checks, CI is usually better than a local pre-commit hook.
A strong answer is:
I use pre-commit hooks for fast checks and CI for heavier validation. Hooks improve feedback, but CI remains the source of truth for team-wide enforcement.
How can we attach an automated script to run when commits are pushed?
What interviewers are testing: Whether you know server-side hooks versus CI for enforcing policy on pushed commits.
Use server-side hooks or CI/CD.
Git server-side hooks include:
pre-receiveupdatepost-receive
Use cases:
| Hook | Use case |
|---|---|
pre-receive |
Reject pushes that violate policy |
update |
Validate individual branch updates |
post-receive |
Trigger notifications or deployment actions |
In modern hosted platforms, CI/CD pipelines often replace custom server hooks for tests and deployments.
A strong answer is:
For push-time automation, I can use server-side hooks or CI/CD. I use hooks for repository policy and CI for build, test, and deployment workflows.
What is the difference between pre-receive, update, and post-receive hooks in Git?
What interviewers are testing: Whether you can differentiate pre-receive, update, and post-receive hook timing and rejection behavior.
These are server-side hooks that run during a push.
| Hook | When it runs | Can reject push? | Common use |
|---|---|---|---|
pre-receive |
Before any refs are updated | Yes | Enforce global push policy |
update |
Before each individual ref is updated | Yes | Enforce branch-specific policy |
post-receive |
After refs are updated | No | Trigger notifications, CI, deployment |
Example:
- Use
pre-receiveto reject a push when any proposed ref update violates a repository-wide policy. - Use
updatefor policy specific to an individual ref or branch. - Use
post-receiveto notify a chat channel.
A strong answer is:
pre-receivecan reject the whole push,updateruns per ref, andpost-receiveruns after acceptance for follow-up actions.
Do we have to store scripts for Git hooks within the same repository?
What interviewers are testing: Whether you understand that hooks are local by default and how teams share hook logic reliably.
Git hooks normally live in the local .git/hooks directory, and they are not automatically shared when someone clones the repository.
To share hook logic across a team, common approaches are:
- Store hook scripts in the repository under a directory such as
.githooks/ - Configure
core.hooksPath - Use tools such as Husky, Lefthook, or pre-commit
- Enforce critical checks in CI or server-side hooks
Example:
git config core.hooksPath .githooksImportant point:
Local hooks are helpful, but they can be skipped or missing. Critical rules should also run in CI or server-side enforcement.
A strong answer is:
Hooks can be versioned in the repo, but local hooks are not automatically shared by default. For reliable enforcement, I combine shared hook setup with CI or server-side checks.
Advanced Git techniques
What is HEAD in Git?
What interviewers are testing: Whether you understand HEAD as a symbolic ref and what detached HEAD means.
HEAD normally stores a symbolic reference to the currently checked-out branch, such as refs/heads/main; that branch ref names the tip commit.
In detached HEAD state, HEAD directly identifies a commit instead of going through a branch ref.
Example:
cat .git/HEADOutput may look like:
ref: refs/heads/mainIf you checkout a specific commit instead of a branch, you enter a detached HEAD state.
A strong answer is:
HEADnormally points to the current branch ref, and that branch ref points to the tip commit. In detached HEAD state,HEADpoints directly to a commit hash instead.
What is git rerere?
What interviewers are testing: Whether you know rerere records conflict resolutions for repeated merges or rebases.
rerere means reuse recorded resolution.
It lets Git remember how you resolved a conflict. If the same conflict appears again, Git can reuse your previous resolution.
Enable it:
git config --global rerere.enabled trueUseful when:
- You repeatedly rebase a long-running branch
- You resolve the same conflicts multiple times
- You work on release branches with repeated backports
A strong answer is:
git rerererecords conflict resolutions and reuses them when the same conflict appears again.
What are the three common versions of git diff command?
What interviewers are testing: Whether you can name the three common git diff comparisons—working tree, staged, and against HEAD.
Common git diff commands are:
| Command | Shows |
|---|---|
git diff |
Working tree changes not staged yet |
git diff --staged |
Staged changes compared with HEAD |
git diff HEAD |
All changes in working tree and staging area compared with HEAD |
--cached is another name for --staged.
Example:
git diff --stagedA strong answer is:
I use
git diffbefore staging,git diff --stagedbefore committing, andgit diff HEADto see all uncommitted changes.
How does Git provide flexibility in version control?
What interviewers are testing: Whether you can explain Git's flexibility across branching, remotes, tags, stash, and workflow styles.
Git is flexible because it supports many workflows and history operations.
Examples:
- Local commits without network access
- Lightweight branching
- Merging and rebasing
- Tags for releases
- Stash for temporary work
- Cherry-pick for selective commits
- Worktrees for multiple working directories
- Hooks for automation
- Remote workflows with multiple remotes
This flexibility supports different team styles:
- Trunk-based development
- Feature branch workflow
- Release branches
- Fork-based open source workflow
A strong answer is:
Git is flexible because it supports local history, cheap branches, multiple remotes, tags, hooks, and different collaboration workflows.
Why is it advisable to create an additional commit instead of amending an existing commit?
What interviewers are testing: Whether you know when a new commit is safer than amending already-shared history.
git commit --amend rewrites the most recent commit and creates a new commit hash.
This is fine for local, unpushed commits.
But if the commit is already pushed and shared, amending it can disrupt other developers because their history still points to the old commit.
Use an additional commit when:
- The commit is already public
- Other developers may have pulled it
- The branch is protected
- You want an auditable fix
Use amend when:
- The commit is local
- You are only fixing the last commit message or small mistake
- No one else depends on it
A strong answer is:
I amend local commits, but for shared commits I usually create a new commit to avoid rewriting public history.
What is a bare repository in Git?
What interviewers are testing: Whether you understand bare repositories as remotes without a working tree.
A bare repository is a Git repository without a working tree.
Create one with:
git init --bareIn a normal repository, Git metadata is stored in .git/.
In a bare repository, the repository metadata is stored directly in the repository directory.
Bare repositories are commonly used as shared remote repositories because no one edits files directly inside them.
A strong answer is:
A bare repository stores Git history but has no checked-out working files. It is useful as a remote repository that developers push to and fetch from.
How can we determine the commit that introduced a bug in Git?
What interviewers are testing: Whether you can use repository history systematically to locate a regression rather than manually checking commits one by one.
Use git bisect.
git bisect uses binary search to find the commit that introduced a bug.
Typical flow:
git bisect start
git bisect bad
git bisect good <known-good-commit>Git checks out a commit between good and bad. You test it and mark it:
git bisect good
# or
git bisect badWhen finished:
git bisect resetA strong answer is:
I use
git bisectwhen I know one commit is good and a later commit is bad. Git narrows the range until it finds the commit that introduced the bug.
How does Git know the tip commit of a branch?
What interviewers are testing: Whether you understand branch refs conceptually and how to inspect them with Git commands instead of assuming loose files always exist.
Git uses refs.
Conceptually, a local branch is a ref such as refs/heads/main that names the branch's tip commit object ID. A loose ref may appear as .git/refs/heads/main, but Git can store refs in other internal formats—including packed refs—so applications should use Git commands rather than depend on that file existing.
Example:
git rev-parse main
git symbolic-ref HEADTraditional repositories use SHA-1 object IDs; Git also supports SHA-256 repository formats.
A strong answer is:
Normally,
HEAD→ a branch ref such asrefs/heads/main→ commit object ID. In detached HEAD state,HEADidentifies the commit directly.
What are the different types of tags you can create in Git?
What interviewers are testing: Whether you know lightweight versus annotated tags and when to sign release tags.
Git has two main types of tags.
| Tag type | Meaning |
|---|---|
| Lightweight tag | Simple pointer to a commit |
| Annotated tag | Full tag object with message, tagger, date, and optional signature |
Create a lightweight tag:
git tag v1.0.0Create an annotated tag:
git tag -a v1.0.0 -m "Release v1.0.0"See Git tag tutorial for create, push, delete, and release tagging.
Push a tag:
git push origin v1.0.0A strong answer is:
Lightweight tags are simple pointers. Annotated tags store extra metadata and are better for official releases.
How can you reorder commits in Git?
What interviewers are testing: Whether you can reorder local commits with interactive rebase before sharing them.
Use interactive rebase.
Example: reorder the last 4 commits:
git rebase -i HEAD~4In the editor, reorder the pick lines.
Example:
pick a1b2c3d Add API endpoint
pick d4e5f6g Add frontend form
pick h7i8j9k Add validation
pick k1l2m3n Add testsImportant warning:
Reordering commits rewrites history. Do this on private/local branches, not shared public branches unless your team agrees.
A strong answer is:
I use interactive rebase to reorder local commits before review. I avoid rewriting shared branch history.
How will you split a commit into multiple commits?
What interviewers are testing: Whether you can split an oversized commit into smaller logical commits during interactive rebase.
Use interactive rebase.
Typical flow:
git rebase -i HEAD~3Mark the commit to split as edit.
When Git stops at that commit:
git reset HEAD~1Now the changes are back in the working tree. Stage and commit them in smaller pieces:
git add part1.js
git commit -m "Add first part"
git add part2.js
git commit -m "Add second part"Then continue:
git rebase --continueA strong answer is:
I split a commit with interactive rebase by stopping at the commit, resetting it, then staging and recommitting the changes in smaller logical pieces.
What is filter-branch in Git?
What interviewers are testing: Whether you understand history-rewrite tools, including that git filter-repo is a separately installed modern alternative to filter-branch.
git filter-branch is an older command used to rewrite Git history across many commits.
It can be used for tasks such as:
- Removing a file from history
- Rewriting author information
- Changing paths across history
However, modern Git interviews should mention that filter-branch is generally discouraged for new work because it is slow and easy to misuse.
Preferred modern options:
git filter-repo— a separately installed tool recommended for modern history-rewrite workflows- BFG Repo-Cleaner — another third-party option for removing large files or secrets
- For legacy workflows, see how to reduce Git repo size with filter-branch — but prefer modern tools for new work
Important warning:
History rewriting affects commit hashes. If the repository is shared, coordinate carefully and rotate any leaked secrets. Removing a secret from Git history does not make the secret safe again.
A strong answer is:
filter-branchrewrites history, but today I would usually usegit filter-repoor BFG. For leaked secrets, I would also rotate the secret, not only remove it from history.
What are the three main trees maintained by Git?
What interviewers are testing: Whether you can explain Git's working tree, index, and HEAD as the three main trees.
Git commonly works with three trees:
| Tree | Meaning |
|---|---|
| HEAD | Last committed snapshot |
| Index / staging area | Proposed next commit |
| Working tree | Files currently checked out and edited |
Typical flow:
Working tree → Index → HEAD
edit git add git commitUseful commands:
| Command | Affects |
|---|---|
git add |
Working tree → index |
git commit |
Index → HEAD |
git restore |
Restore working tree changes |
git reset |
Move HEAD or change index/working tree depending on mode |
See Git restore explained with examples for unstaging and undoing file changes.
A strong answer is:
The working tree contains my current files, the index contains what I plan to commit, and HEAD points to the last committed snapshot.
Tooling and interoperability
What is an upstream or tracking branch in Git?
What interviewers are testing: Whether you understand how a local branch knows which remote branch to fetch from and push to.
An upstream (tracking) branch links a local branch to a remote-tracking ref such as origin/main.
When upstream is set:
git statuscan report ahead/behind countsgit pullandgit pushcan use defaults without repeating remote and branch names
Set upstream on first push:
git push -u origin feature/loginOr configure it explicitly:
git branch --set-upstream-to=origin/feature/loginA strong answer is:
An upstream branch tells my local branch which remote branch it tracks. After
git push -u,git pullandgit pushknow where to synchronize without extra arguments.
What is the difference between git restore, git reset, and git revert?
What interviewers are testing: Whether you pick the right undo mechanism instead of using one command for every recovery scenario.
| Command | Typical use | Shared history safe? |
|---|---|---|
git restore |
Discard or restore working-tree or staged file changes | Yes (does not rewrite commits) |
git reset |
Move branch ref; optionally change index/working tree (--soft, --mixed, --hard) |
Risky on public branches when moving refs |
git revert |
Create a new commit that undoes an earlier commit | Yes |
Examples:
git restore file.js
git restore --staged file.js
git reset --soft HEAD~1
git revert <commit>A strong answer is:
I use
restorefor file-level undo,resetto move branch history or unstage, andrevertwhen I need to undo a public commit without rewriting shared history.
What are shallow and partial clones in Git?
What interviewers are testing: Whether you know Git can intentionally download less than a full repository when history or objects are huge.
A normal clone copies the project's history and sets up remote-tracking refs.
A shallow clone limits history depth:
git clone --depth 1 https://github.com/user/large-repo.gitUseful for CI or situations where you only need recent history.
Partial clone reduces which Git objects are fetched initially, while sparse checkout limits which tracked paths are populated in the working tree. They are often useful together for very large repositories.
Trade-off: shallow or partial clones may lack older commits locally, so some history operations need a deeper fetch first.
A strong answer is:
Shallow clones reduce history depth; partial clone and sparse checkout address object fetch and working-tree size separately. I use them for CI or huge repos, then deepen history only when debugging needs it.
What is the difference between a merge commit, squash merge, and rebase merge?
What interviewers are testing: Whether you can explain how a pull request lands on the target branch and why teams choose different integration styles.
These are platform or team policies for integrating a feature branch—not three different core Git commands with identical names everywhere.
| Style | What it does | Trade-off |
|---|---|---|
| Merge commit | Creates a merge commit that joins feature and target branch histories | Preserves branch topology; history can look busier |
| Squash merge | Combines feature commits into one commit on the target branch | Cleaner mainline history; loses per-commit feature detail on main |
| Rebase merge | Replays feature commits onto the target tip, then fast-forwards | Linear history on main; rewrites feature commits as they land |
Example on the command line, a merge commit is the classic:
git switch main
git merge feature/loginSquash workflows are common on GitHub/GitLab pull requests. Rebase-and-merge replays commits onto updated main before integration.
A strong answer is:
A merge commit keeps full branch history, squash merge collapses a feature into one commit on main, and rebase merge replays commits for a linear mainline—I pick based on team policy and how much history we want preserved.
What is shortlog in Git?
What interviewers are testing: Whether you can summarize contributor activity with git shortlog for release notes.
git shortlog summarizes commit history, usually grouped by author.
It is useful for:
- Release notes
- Contributor summaries
- Reviewing who contributed what
- Summarizing commits between versions
Examples:
git shortlog
git shortlog -sn
git shortlog v1.0.0..v1.1.0Common options:
| Option | Meaning |
|---|---|
-s |
Show only commit counts |
-n |
Sort by number of commits |
-e |
Show email addresses |
A strong answer is:
git shortloggives a release-friendly summary of commit history, often grouped by author.
Some people use git checkout and some use git co for checkout. How is that possible?
What interviewers are testing: Whether you understand Git aliases and that shortcuts like git co are not built-in commands by default.
git co is usually a Git alias. The built-in command is git checkout — see our Git checkout command guide for branch, commit, and file checkout patterns.
You can create aliases with git config.
Example:
git config --global alias.co checkoutAfter that, this works:
git co mainCommon aliases:
git config --global alias.st status
git config --global alias.br branch
git config --global alias.cm commit
git config --global alias.lg "log --oneline --graph --decorate"A strong answer is:
git cois not a built-in Git command by default. It works when someone has configured it as an alias forgit checkout.
What is git grep?
What interviewers are testing: Whether you know git grep searches tracked content and specific trees in history.
git grep searches for a string or regular expression in tracked Git files.
Example:
git grep "TODO"Search with line numbers:
git grep -n "handleLogin"Search in a specific commit or branch:
git grep "oldFunction" HEAD~1
git grep "apiUrl" mainWhy use it:
- Fast code search inside a repository
- Can search committed trees, not only current files
- Useful during debugging and refactoring
A strong answer is:
git grepsearches tracked files or a specific Git tree for text patterns. I use it when I want Git-aware code search.
What is a submodule in Git?
What interviewers are testing: Whether you understand submodule pointers, initialization, and the workflow complexity they add.
A Git submodule lets a parent repository reference another Git repository at a specific commit.
The parent records the submodule path and the exact commit it expects, while the submodule keeps its own independent history.
Common use cases:
- Shared library used by multiple projects
- Vendor dependency that must be pinned to a specific commit
- Keeping separate repositories while composing them together
Add a submodule:
git submodule add https://github.com/user/library.git libs/libraryClone a repository with submodules:
git clone --recurse-submodules <repo-url>Initialize submodules after cloning:
git submodule update --init --recursiveImportant trade-off:
Submodules give clear version pinning, but they add workflow complexity. Developers must remember to update, initialize, and commit submodule pointer changes.
A strong answer is:
A submodule lets one repository pin another repository to a specific commit. It keeps histories separate, but developers must initialize and update the submodule explicitly.

