Git Interview Questions and Answers


What is Git?
  • Git is a free and open-source distributed version control system (DVCS) designed to handle everything from small to very large projects with speed and efficiency.
What is version control? Why is it important?
  • Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later. It's important for:
    • Tracking changes and history.
    • Collaborating with others.
    • Backing up your work.
    • Experimenting with new features without affecting the main codebase.
    • Undoing mistakes.
Explain the difference between centralized and distributed version control systems.
  • Centralized VCS: All users connect to a single central server to get the latest version of files and commit their changes. Examples: SVN, CVS.
    • Pros: Easier to set up and manage.
    • Cons: Single point of failure (if the server goes down, no one can work or commit). Requires an internet connection to work.
  • Distributed VCS: Every user has a complete copy of the repository, including the full history. Examples: Git, Mercurial.
    • Pros: No single point of failure. Can work offline. Faster operations (most operations are local).
    • Cons: Can be slightly more complex to understand initially.
What is a Git repository?
  • A Git repository is a directory (or folder) that contains all the project files and the complete history of changes made to those files. It includes the .git folder, which is where Git stores all its data.
Explain the three states of files in Git.
  • Working Directory: The files you are currently working on.
  • Staging Area (Index): A temporary area where you prepare changes to be committed. Files in the staging area are marked to be included in the next commit.
  • Git Repository: Where Git permanently stores the committed snapshots of your project.
What is a commit in Git?
  • A commit is a snapshot of your project's files at a specific point in time. It's a record of changes that you have decided to save. Each commit has a unique identifier (hash) and includes metadata like the author, date, and a commit message.
What is the purpose of the .git folder?
  • The .git folder contains all the necessary files and data for your Git repository. This includes the commit history, branches, tags, configuration, and other internal Git objects. You should generally not manually modify files within this folder.
How do you initialize a new Git repository?
  • Use the command git init in the root directory of your project.
How do you clone an existing Git repository?
  • Use the command git clone .
What is the purpose of the git status command?
  • git status shows the state of your working directory and staging area. It tells you which files are untracked, modified, and staged for the next commit.
How do you add changes to the staging area?
  • To add a specific file: git add .
  • To add all modified and untracked files: git add . or git add -A.
How do you commit staged changes?
  • Use the command git commit -m "Your commit message". The -m flag allows you to provide a commit message directly.
What makes a good commit message?
  • A good commit message is concise, descriptive, and explains *why* the changes were made, not just *what* was changed. A common convention is a short subject line (50 chars or less) followed by a blank line and a more detailed body.
How do you view the commit history?
  • Use the command git log.
  • Useful options: git log --oneline (concise history), git log --graph --oneline --all (visualizing branches and merges).
How do you view the difference between the working directory and the staging area?
  • Use the command git diff.
How do you view the difference between the staging area and the last commit?
  • Use the command git diff --staged or git diff --cached.
How do you view the difference between two commits?
  • Use the command git diff .
How do you unstage changes from the staging area?
  • For a specific file: git reset HEAD (older Git versions) or git restore --staged (newer Git versions).
How do you discard changes in the working directory?
  • For a specific file: git checkout -- (older Git versions) or git restore (newer Git versions).
  • To discard all unstaged changes: git checkout -- . or git restore ..
How do you undo the last commit? (keeping changes)
  • Use the command git reset HEAD~1. This moves the branch pointer back one commit but keeps the changes in your working directory and staging area.
How do you undo the last commit? (discarding changes)
  • Use the command git reset --hard HEAD~1. This moves the branch pointer back one commit and discards all changes from that commit. **Use with caution, as this is destructive.**
What is the purpose of the .gitignore file?
  • The .gitignore file specifies intentionally untracked files that Git should ignore. This is typically used for build artifacts, temporary files, IDE configuration files, and sensitive information.
What is a Git branch? Why are branches important?
  • A branch is essentially a lightweight movable pointer to a commit. It represents an independent line of development. Branches are important because they allow multiple developers to work on different features or bug fixes concurrently without interfering with each other's work.
What is the default branch name in Git?
  • Historically, it was master. In newer Git versions and platforms like GitHub, the default is now commonly main.
How do you create a new branch?
  • Use the command git branch . This creates the branch but does not switch to it.
How do you switch to an existing branch?
  • Use the command git checkout (older Git versions) or git switch (newer Git versions).
How do you create a new branch and switch to it immediately?
  • Use the command git checkout -b (older Git versions) or git switch -c (newer Git versions).
How do you list all local branches?
  • Use the command git branch. The current branch will be marked with an asterisk (*).
How do you list all remote branches?
  • Use the command git branch -r.
How do you list all local and remote branches?
  • Use the command git branch -a.
What is the purpose of merging branches?
  • Merging is the process of combining the changes from one branch into another. Git attempts to integrate the histories of the two branches.
How do you merge one branch into another?
  • First, switch to the branch you want to merge *into* (the target branch): git checkout .
  • Then, merge the source branch: git merge .
What is a merge conflict? When does it occur?
  • A merge conflict occurs when Git cannot automatically merge changes because both branches have modified the same lines in a file, or one branch deleted a file that the other modified.
How do you resolve a merge conflict?
  • Git will mark the conflicting areas in the files.
  • You manually edit the files to resolve the conflicts, choosing which changes to keep.
  • Add the resolved files to the staging area: git add .
  • Complete the merge by committing: git commit (Git will often provide a default commit message).
How do you abort a merge?
  • Use the command git merge --abort. This reverts the repository to the state before the merge attempt.
How do you delete a local branch?
  • Use the command git branch -d . This deletes the branch if it has been fully merged.
  • To force delete an unmerged branch: git branch -D . **Use with caution.**
What is a remote repository?
  • A remote repository is a version of your project hosted on the internet or a network (e.g., on GitHub, GitLab, Bitbucket). It serves as a central point for collaboration and backup.
How do you add a remote repository to your local repository?
  • Use the command git remote add . The common remote name is origin.
How do you view the remotes configured for your repository?
  • Use the command git remote -v.
How do you push local commits to a remote repository?
  • Use the command git push .
  • For the first push of a new branch, you might use git push -u origin to set the upstream branch.
How do you fetch changes from a remote repository?
  • Use the command git fetch . This downloads the commits and objects from the remote but does not merge them into your current branch.
How do you pull changes from a remote repository?
  • Use the command git pull . This is a combination of git fetch and git merge (by default).
What is the difference between git fetch and git pull?
  • git fetch downloads changes from the remote but does not integrate them into your current branch. It updates the remote-tracking branches (e.g., origin/main).
  • git pull downloads changes and automatically merges them into your current branch. It's equivalent to git fetch followed by git merge (or git rebase if configured).
How do you delete a remote branch?
  • Use the command git push --delete or git push :.
What is the purpose of the HEAD pointer?
  • HEAD is a pointer to the current commit you are working on. It usually points to the tip of the current branch.
What is the purpose of the origin remote name?
  • origin is the conventional default name given to the remote repository from which you initially cloned the project.
What is the difference between git reset --soft, git reset --mixed, and git reset --hard? (Advanced)
  • git reset --soft : Moves the branch pointer to the specified commit, but keeps the changes from the undone commits in the staging area.
  • git reset --mixed (default): Moves the branch pointer to the specified commit, and moves the changes from the undone commits to the working directory (unstaged).
  • git reset --hard : Moves the branch pointer to the specified commit and discards all changes from the undone commits in both the staging area and working directory. **Use with extreme caution.**
What is rebasing in Git?
  • Rebasing is the process of moving or combining a sequence of commits to a new base commit. It essentially rewrites the commit history, making it appear as if your changes were made on top of the target branch from the beginning. It's often used to create a cleaner, linear history compared to merging.
What is the difference between merging and rebasing?
  • Merging: Creates a new merge commit that combines the histories of two branches. Preserves the original commit history.
  • Rebasing: Rewrites the commit history by moving your commits to the tip of another branch. Creates a linear history but changes the commit hashes.
When should you use merging vs. rebasing?
  • Use merging when you want to preserve the exact history of your branches, including merge commits. This is often preferred for shared or public branches (like main or develop).
  • Use rebasing when you want a clean, linear history, especially for feature branches that you are working on privately before merging into a shared branch. **Avoid rebasing commits that have already been pushed to a public repository.**
What is interactive rebasing?
  • Interactive rebasing (git rebase -i ) allows you to modify the commits being rebased. You can reorder, edit, squash (combine), or drop commits, providing a powerful way to clean up your commit history.
What is stashing in Git?
  • Stashing allows you to save your current changes (both staged and unstaged) temporarily without committing them. This is useful when you need to switch to another branch or work on something else without committing incomplete work.
How do you stash your current changes?
  • Use the command git stash or git stash push.
How do you view your stashed changes?
  • Use the command git stash list.
How do you apply stashed changes?
  • To apply the most recent stash and keep it in the stash list: git stash apply.
  • To apply the most recent stash and remove it from the stash list: git stash pop.
  • To apply a specific stash: git stash apply stash@{} or git stash pop stash@{}.
How do you delete stashed changes?
  • To drop the most recent stash: git stash drop.
  • To drop a specific stash: git stash drop stash@{}.
  • To clear all stashes: git stash clear.
What is a Git tag?
  • A tag is a pointer to a specific commit, typically used to mark important points in history, such as releases (e.g., v1.0, v2.0).
What is the difference between a lightweight tag and an annotated tag?
  • Lightweight tag: A simple pointer to a commit. It's just a name. Created with git tag .
  • Annotated tag: Stores more information, including the tagger name, email, date, and a tagging message. It's stored as a full object in the Git database. Created with git tag -a -m "Tag message". Annotated tags are generally recommended for releases.
How do you create a tag?
  • Lightweight: git tag
  • Annotated: git tag -a -m "Tag message"
How do you push tags to a remote repository?
  • By default, git push does not push tags. You need to explicitly push them:
    • Push a specific tag: git push .
    • Push all tags: git push --tags.
What is the purpose of git cherry-pick? (Advanced)
  • git cherry-pick allows you to apply a single commit from one branch to another branch. It's useful for applying a specific bug fix from a feature branch to the main branch without merging the entire feature branch.
What is the purpose of git bisect? (Advanced)
  • git bisect is a debugging tool that helps you find the commit that introduced a bug by performing a binary search through your commit history.
What is the difference between git remote add origin and git clone ?
  • git clone : Downloads an existing remote repository to your local machine, including the full history. It automatically sets up the remote as origin.
  • git remote add origin : Adds a new remote repository to an *existing* local repository. It does not download the history.
How do you change the remote URL of a repository?
  • Use the command git remote set-url .
What is the purpose of the git log --graph command?
  • git log --graph displays the commit history as a graph, showing branching and merging relationships visually.
What is the purpose of the git log --oneline command?
  • git log --oneline displays each commit on a single line, showing the commit hash and the subject line of the commit message.
How do you view the history of a specific file?
  • Use the command git log .
How do you see who last modified each line of a file?
  • Use the command git blame .
What is the purpose of the git clean command? (Advanced)
  • git clean is used to remove untracked files from your working directory.
    • git clean -n: Shows what would be removed without actually removing anything.
    • git clean -f: Removes untracked files (use with caution).
    • git clean -df: Removes untracked files and directories.
What is the purpose of the git revert command?
  • git revert creates a new commit that undoes the changes introduced by the specified commit. Unlike git reset, it does not rewrite history, making it safe to use on shared branches.
What is the difference between git reset and git revert?
  • git reset moves the branch pointer and potentially modifies the working directory and staging area. It rewrites history (unless using --soft or --mixed locally).
  • git revert creates a new commit that undoes changes. It does not rewrite history and is safe for public branches.
How do you fetch changes from a remote without merging? (Revisited)
  • Use the command git fetch .
How do you pull changes from a remote using rebasing instead of merging?
  • Use the command git pull --rebase . You can also configure this as the default behavior for a branch.
What is the purpose of the git stash apply vs. git stash pop? (Revisited)
  • git stash apply applies the stashed changes but leaves the stash in the stash list.
  • git stash pop applies the stashed changes and removes the stash from the stash list.
How do you configure Git to use a different editor for commit messages?
  • Use the command git config --global core.editor "" (e.g., "code --wait" for VS Code).
How do you set up an alias for a Git command?
  • Use the command git config --global alias. "" (e.g., git config --global alias.ci "commit -m").
What is the purpose of the git reflog command? (Advanced)
  • git reflog shows a log of where your HEAD and branch references have been. It's a powerful tool for recovering lost commits or undoing actions that rewrote history (like git reset --hard).
How do you recover a lost commit using git reflog? (Advanced)
  • Use git reflog to find the commit hash of the lost commit.
  • Use git cherry-pick or git branch to recover it.
What is a detached HEAD state?
  • A detached HEAD state occurs when HEAD points directly to a commit hash instead of pointing to the tip of a branch. This happens when you check out a specific commit or a remote-tracking branch. Commits made in a detached HEAD state are not part of any branch by default and can be lost if you switch branches without creating a new branch first.
How do you exit a detached HEAD state?
  • Create a new branch at the current commit: git branch and then switch to that branch: git checkout .
  • Switch back to an existing branch: git checkout (be aware that commits made in the detached HEAD state will be lost unless you created a branch for them).
What is the purpose of the git log --decorate command?
  • git log --decorate shows the names of branches and tags that point to each commit in the log output.
What is the purpose of the git log --stat command?
  • git log --stat shows a summary of the changes (files modified, lines added/deleted) for each commit.
How do you squash multiple commits into a single commit?
  • Using interactive rebase: git rebase -i HEAD~. Mark the commits you want to squash with the squash or fixup command.
What is the difference between squash and fixup during interactive rebase?
  • squash: Combines the commit into the previous one and allows you to edit the combined commit message.
  • fixup: Combines the commit into the previous one and discards the current commit's message, using the previous commit's message.
What is the purpose of the git push --force command? (Advanced)
  • git push --force overwrites the remote branch with your local branch, regardless of whether the remote branch has newer commits. **Use with extreme caution, especially on shared branches, as it can cause other developers to lose their work.**
When might you use git push --force-with-lease instead of git push --force? (Advanced)
  • git push --force-with-lease is a safer alternative to --force. It only force pushes if the remote branch has not been updated since you last pulled. This helps prevent overwriting changes that others have pushed.
What is the purpose of Git hooks? (Advanced)
  • Git hooks are scripts that Git executes automatically at certain points in its workflow (e.g., before a commit, after a merge, before a push). They can be used to automate tasks like running tests, linting code, or enforcing commit message conventions.
Where are Git hooks stored?
  • Git hooks are stored in the .git/hooks directory within your repository.
Name some common Git hooks.
  • pre-commit: Runs before a commit.
  • prepare-commit-msg: Used to edit the default commit message.
  • commit-msg: Used to validate a commit message.
  • post-commit: Runs after a commit.
  • pre-push: Runs before a push.
  • pre-rebase: Runs before a rebase.
What is the purpose of the git archive command? (Advanced)
  • git archive creates an archive (like a zip or tar file) of the contents of a specific commit, branch, or tag. It's useful for creating release archives without the .git directory.
How do you create a patch file from a commit? (Advanced)
  • Use the command git format-patch -1 (for a single commit) or git format-patch .. (for a range of commits).
How do you apply a patch file? (Advanced)
  • Use the command git apply .
What is the purpose of Git submodules? (Advanced)
  • Git submodules allow you to include another Git repository as a subdirectory within your main repository. This is useful for managing dependencies or components that are developed independently.
What are the potential drawbacks of using Git submodules? (Advanced)
  • Can be complex to manage, especially with nested submodules.
  • Requires extra commands to initialize and update submodules (git submodule init, git submodule update).
  • Can lead to confusion if not all team members understand how submodules work.
What are Git worktrees? (Advanced)
  • Git worktrees allow you to have multiple working directories associated with a single repository. This is useful for working on multiple branches simultaneously without having to switch branches in your main working directory.
How do you create a Git worktree? (Advanced)
  • Use the command git worktree add [].
How do you list existing Git worktrees? (Advanced)
  • Use the command git worktree list.
How do you remove a Git worktree? (Advanced)
  • Use the command git worktree remove .
What is the purpose of the git gc command? (Advanced)
  • git gc (garbage collect) cleans up unnecessary files and optimizes the local repository. It's typically run automatically by Git but can be run manually.
What is the difference between fetching and pulling a remote-tracking branch?
  • Fetching a remote-tracking branch (e.g., origin/main) updates its pointer to match the remote.
  • Pulling a remote-tracking branch is not a common operation. You typically pull from a remote branch into a local branch (e.g., pull origin/main into your local main).
How do you view the remote branches you have fetched?
  • Use the command git branch -r.
How do you compare your local branch with its remote-tracking branch?
  • Use the command git diff / (e.g., git diff main origin/main).
What is the purpose of the git stash branch command? (Advanced)
  • git stash branch creates a new branch from the commit where the stash was created and applies the stashed changes to that new branch. It then drops the stash.
How do you clone a repository without the full history (shallow clone)? (Advanced)
  • Use the command git clone --depth . This is useful for saving disk space or when you only need the recent history.
How do you update a shallow clone to include more history? (Advanced)
  • Use the command git fetch --unshallow or git pull --unshallow.
What is the purpose of the git ls-tree command? (Advanced)
  • git ls-tree lists the contents of a tree object (which represents a directory snapshot at a specific commit). It shows the file modes, object types, object hashes, and filenames.
What is the purpose of the git cat-file command? (Advanced)
  • git cat-file -p displays the content of a Git object (commit, tree, blob, tag) in a human-readable format.
What is the purpose of the git update-ref command? (Advanced)
  • git update-ref is a low-level command used to update the object name stored in a reference (like a branch or tag). It's not typically used in day-to-day Git operations.
How do you configure Git to ignore file mode changes?
  • Use the command git config core.fileMode false. This is useful on platforms where file permissions might change unexpectedly.
How do you resolve merge conflicts using a merge tool?
  • Configure a merge tool in Git (e.g., using git config --global merge.tool ).
  • During a merge conflict, run git mergetool to open the configured merge tool and resolve the conflicts visually.
What is the purpose of the git rerere command? (Advanced)
  • git rerere (reuse recorded resolution) helps Git remember how you resolved past merge conflicts. If the same conflict occurs again, Git can automatically apply the previously recorded resolution.
How do you enable git rerere? (Advanced)
  • Use the command git config --global rerere.enabled true.
What is the purpose of the git stash save command? (Deprecated, now use git stash push)
  • git stash save "message" was used to stash changes with a descriptive message. It's now superseded by git stash push -m "message".
What is the purpose of the git clean -x command? (Advanced)
  • git clean -x removes ignored files in addition to untracked files. Use with extreme caution!
How do you create a bare repository?
  • Use the command git init --bare. A bare repository does not have a working directory; it only contains the contents of the .git folder. Bare repositories are typically used as central repositories for collaboration.
What is the difference between a regular repository and a bare repository?
  • A regular repository has a working directory where you can modify files and a .git folder.
  • A bare repository only has the contents of the .git folder and is intended for sharing and pushing/pulling from.
What is the purpose of the git remote prune command?
  • git remote prune removes any remote-tracking branches that no longer exist on the remote repository.
How do you rename a local branch?
  • If you are on a different branch: git branch -m .
  • If you are on the branch you want to rename: git branch -m .
How do you rename a remote branch?
  • Rename the local branch: git branch -m .
  • Delete the old remote branch: git push --delete .
  • Push the new local branch and set it as upstream: git push -u .
What is the purpose of the git config --list command?
  • git config --list shows all the Git configuration settings (system, global, and local).
What is the purpose of the git check-ignore command?
  • git check-ignore helps you understand why a specific file is being ignored by Git, showing which pattern in which .gitignore file is causing it to be ignored.
What is the purpose of the git add -p command? (Advanced)
  • git add -p (patch mode) allows you to interactively stage parts of modified files, rather than staging the entire file. This is useful for creating granular commits.
What is the purpose of the git checkout -p command? (Advanced)
  • git checkout -p (patch mode) allows you to interactively discard parts of modified files in your working directory.
What is the purpose of the git reset -p command? (Advanced)
  • git reset -p (patch mode) allows you to interactively unstage parts of changes that are currently in the staging area.
What is the purpose of the git commit --amend command? (Revisited)
  • git commit --amend is used to modify the most recent commit. You can add newly staged changes to the last commit or just modify the commit message. **Avoid amending commits that have already been pushed to a public repository.**
How do you share a local commit without pushing to a remote? (Advanced)
  • You can create a patch file (git format-patch) and share the patch file.
  • You can bundle commits into a single file (git bundle).
What is the purpose of the git bundle command? (Advanced)
  • git bundle create creates a single file that contains the Git history up to the specified branch or tag. This file can be transferred and cloned or fetched from by another Git repository.
How do you clone from a Git bundle? (Advanced)
  • Use the command git clone .
What is the purpose of the git cherry command? (Advanced)
  • git cherry [] shows which commits on the head branch have not been merged into the upstream branch.
What is the purpose of the git notes command? (Advanced)
  • git notes allows you to add arbitrary notes to Git objects (like commits) without changing the commit history. This is useful for adding supplementary information that isn't part of the original commit message.
How do you create a Git submodule? (Advanced)
  • Use the command git submodule add .
How do you update Git submodules? (Advanced)
  • Use the command git submodule update --init --recursive to initialize and update submodules.
How do you remove a Git submodule? (Advanced)
  • Remove the submodule entry from .gitmodules.
  • Remove the submodule directory.
  • Unstage and commit the changes.
  • Remove the submodule from Git's cache: git rm --cached .
What is the purpose of the git fsck command? (Advanced)
  • git fsck (file system check) verifies the integrity of the Git repository's file system. It can find corrupted or dangling objects.
What is the purpose of the git blame -w command?
  • git blame -w ignores whitespace changes when performing the blame operation.
What is the purpose of the git stash push -u command? (Advanced)
  • git stash push -u includes untracked files in the stash. By default, git stash only stashes tracked files.
What is the purpose of the git stash show command?
  • git stash show displays the changes included in the most recent stash. You can also specify a stash index (e.g., git stash show stash@{1}).
What is the purpose of the git clean -d command?
  • git clean -d removes untracked directories in addition to untracked files.
How do you list all remote-tracking branches? (Revisited)
  • Use the command git branch -r.
How do you track a remote branch locally?
  • Use the command git checkout --track / (e.g., git checkout --track origin/feature/new-feature). This creates a new local branch with the same name and sets up the upstream tracking. A simpler way is often just git checkout , and Git will often offer to create a tracking branch.
What is the purpose of the git config --global core.autocrlf?
  • This setting handles line ending conversions between different operating systems.
    • true (Windows): Git converts CRLF to LF on commit and LF to CRLF on checkout.
    • input (macOS/Linux): Git converts CRLF to LF on commit (prevents committing CRLF endings).
    • false: Git does not perform any line ending conversions.
What is the difference between git fetch --all and git pull --all?
  • git fetch --all fetches all branches from all configured remotes.
  • git pull --all pulls all branches from all configured remotes (which is generally not recommended as it can lead to unexpected merges).
What is the purpose of the git remote update command?
  • git remote update is similar to git fetch --all; it fetches updates from all configured remotes.
What is the purpose of the git push --tags command? (Revisited)
  • git push --tags pushes all local tags to the remote repository.
How do you delete a remote tag?
  • Use the command git push --delete .
What is the purpose of the git diff --name-only command?
  • git diff --name-only shows only the names of the files that are different, without showing the actual content changes.
What is the purpose of the git diff --stat command?
  • git diff --stat shows a summary of the changes, including the files modified and the number of lines added or deleted.
How do you compare a local branch with a remote branch? (Revisited)
  • Use the command git diff /.
  • Use git log ../ to see commits on the remote that are not in your local branch.
  • Use git log /.. to see commits on your local branch that are not on the remote.
What is the purpose of the git apply --check command? (Advanced)
  • git apply --check checks if a patch file can be applied cleanly to the current working directory without actually applying it.
What is the purpose of the git commit --allow-empty command?
  • git commit --allow-empty creates a commit even if there are no changes in the staging area. This can be useful for marking a specific point in history or triggering CI/CD pipelines.