Top 30 GIT Interview Questions Asked in 2023 - IQCode

What is Git and Why is it Used?

Git is a widely used, open-source distributed version control system (DVCS) that efficiently handles the development of small and large projects. It is especially suitable for team collaboration, allowing developers to track changes to the project and easily identify who made those changes. With Git's versioning system, developers can run tests, fix bugs, and add new features while also being able to revert to previous version if necessary without losing any data.

Git is not just popular among software developers, but also documentation teams or anyone who works collaboratively. While learning Git can be challenging at first, it ultimately simplifies the development process, provides an amazing branching system that supports nonlinear development and holds developers accountable for their code which makes the development process more efficient and faster.

Scope of Git

Git enjoys wide popularity because of its well-established version control system and support for collaborative work. With Git's branching system and history tracking capabilities, it can be used for a variety of work beyond software development, such as documentation and other collaborative projects.

Basic Git Interview Questions

  • What is a Version Control System (VCS)?

What is a Git Repository?

A Git repository is a version control system that allows developers to manage changes to their codebase. It stores all of the project's files, as well as a history of changes made to those files. This enables developers to track the evolution of the codebase over time, collaborate with other team members, and revert changes if necessary.

Git

is a distributed version control system created by Linus Torvalds in 2005. It is widely used in software development to manage codebases of all sizes, from small personal projects to large enterprise applications. Git repositories can be hosted locally or remotely, and can be accessed by multiple developers at the same time.

Explanation of the Functionality of Git Clone

Git clone

is a git command that allows us to make a copy of a remote repository from GitHub, Bitbucket, or any other git provider. When we run

git clone

followed by the URL of a repository, it creates a copy or clone of the repository on our local machine.

This is useful when we want to work on a project that already exists in a git repository, or when we want to contribute to an open source project hosted on GitHub. Once we have a local copy of the repository, we can make changes, commit them, and push them back to the origin.

What is the function of the "git config" command?

The "git config" command is used to set and get repository or global options. It can be used to configure a user name, email, preferred editor, file formats, and more. The configuration files are stored in the user's home directory. Git config can be used at three distinct levels: system, user, and repository. System-level configuration affects all users on the machine, user-level affects only the user running the command, and repository-level configuration affects the specific Git repository.

Head in Git and the Number of Heads in a Repository

In Git, a "head" refers to a pointer to a specific commit on a branch. It is essentially a reference to the most recent commit on a specific branch.

A repository in Git can have multiple branches and each branch can have its own head. This means that there can be multiple heads in a repository, with each head pointing to the most recent commit of its respective branch.

To view the heads present in a repository, you can use the command `git branch`, which will list all the branches in the repository along with the current active branch. The active branch will have an asterisk (*) in front of it while all the other branches will be listed as "headless" until a commit is made on them.

Understanding how to manage heads in a Git repository is important when collaborating with others and working on multiple features or versions of a project. Overall, Git provides an efficient way to manage and keep track of multiple heads in a repository.

Understanding Conflict

Conflict refers to a disagreement or clash between two or more entities, which arises due to differences in interests, opinions, or perspectives. In certain cases, conflict can escalate to the point of becoming violent or destructive, leading to the loss of life, property, or resources.

//Sample Code
let num1 = 5;
let num2 = 10;
//check if num1 is greater than num2
if(num1 > num2){
   console.log("num1 is greater than num2");
} else {
   console.log("num1 is less than or equal to num2");
}

In this example, two variables num1 and num2 are compared using an if-else statement. If num1 is greater than num2, then the console will log "num1 is greater than num2". Otherwise, the console will log "num1 is less than or equal to num2".

What is the functionality of "git ls-tree" command?

The "git ls-tree" command is used to display the contents of a specific Git tree object. It shows the file and directory names, along with the mode and type of each item in the tree. This command is helpful when you want to check the contents of a certain commit or branch, or to see the details of a specific file or folder within a Git repository.

What is the purpose of the "git status" command?

The "git status" command is used in the Git version control system to display the current status of local and tracked changes within a repository. This command will show which changes have been made, which files have been added or deleted, and if any changes have been staged for committing. The output of "git status" helps developers keep track of the progress of their work and identify any potential issues before committing changes to the repository.

git status


Definition of "Index"

"Index" is a term used in various fields such as finance, statistics, and library science. It generally refers to a measure or indicator that represents or summarizes the performance or characteristics of a particular group, category, or set of data.

What does the "git add" command do?

The "git add" command is used in Git version control to stage changes made to a file or multiple files for committing to the repository. When changes are made to a file, Git tracks them by the file's hash, which is calculated based on the file's contents. By using "git add", Git takes a snapshot of the file and creates a new hash for it. This snapshot is then saved in the staging area, also known as the index. Once the file is staged, it is ready to be committed to the repository using "git commit".

Intermediate Git Interview Questions

11. Why is Git considered easy to work with?

Git is considered easy to work with due to its simplicity and intuitive design. The basic structure of Git revolves around its main components: the working directory, the staging area, and the Git repository. This allows for easy tracking of changes, committing, and branching. Additionally, Git's commands are straightforward and easy to learn, making it accessible for beginners and experts alike. The ability to work offline and the option to manipulate the Git repository's history are additional features that make Git a popular choice for version control.

Creating a Git Repository

To create a Git repository, follow these steps:

1. Open your terminal or command prompt. 2. Navigate to the directory where you want to create the repository. 3. Type the command "git init" and press enter. 4. Your Git repository is now created and you can start adding files and making commits.

It's important to note that you should only create a Git repository for your project's root directory, not every subdirectory. This helps keep your repository organized and easier to manage.Git stash is a command in Git that allows you to temporarily save your work, or changes, without committing them to the repository. This is useful when you need to switch to a different branch to work on something else but you do not want to commit your changes yet. Stashing your changes allows you to switch to another branch with a clean working directory. You can then apply your stashed changes later on when you switch back to the original branch using the git stash apply or git stash pop command. This is a helpful feature in Git for managing your workflow and keeping your repository organized.H3 tag: Deleting a Branch in Git

The command used to delete a branch in Git is:

Code: `git branch -d branch_name`

Replace "branch_name" with the name of the branch that you want to delete. If the branch has not been merged with the master branch, you can use `-D` instead of `-d` to force delete the branch.

It's important to note that when you delete a branch, all of the commits that were unique to that branch will also be deleted. Make sure that you have merged any important changes into the master branch before deleting a branch.

Differences between "git remote" and "git clone"

"git remote" is a command used to view the aliases for remote repositories whereas "git clone" is a command used to create a copy of a remote repository locally on your computer.

When using "git remote", you can add, remove, or rename aliases for remote repositories. These aliases can then be used instead of the full URL when running other git commands that involve the remote repository.

On the other hand, "git clone" is used to create a local copy of a remote repository on your machine. This command creates a new directory with all the files and commit history from the remote repository, allowing you to make changes to the code locally and push those changes back to the remote repository.

Overall, "git remote" is used for managing aliases for your existing remote repositories, while "git clone" is used to make a local copy of a remote repository.

Explanation of the git stash apply command

The `git stash apply` command is used to apply the changes made to a previous stash. When a developer stashes changes using the `git stash` command, these changes are saved in a stack-like structure. This allows the developer to switch to a different branch or commit without committing their changes or losing their changes entirely.

The `git stash apply` command applies the latest stash by default. However, a specific stash can be applied by including its index after the apply command, such as `git stash apply stash@{2}`.

It is important to note that applying a stash does not remove it from the stash stack. To remove it, the developer should run the `git stash drop` command. If the developer wants to apply the stash and remove it from the stack at the same time, the `git stash pop` command can be used instead.

Difference Between Git Pull and Git Fetch

Git Pull and Git Fetch are two different commands in Git that are used to update the local repository with changes made in the remote repository.

Git Fetch updates the local repository by getting the latest changes from the remote repository, but it does not merge these changes with the local repository. This means that the changes are not applied to the current working branch, and the developer has to manually merge the changes using the Git Merge command.

Git Pull, on the other hand, updates the local repository and merges the changes with the current working branch. It fetches the latest changes from the remote repository and automatically updates the local repository. This means that the developer does not need to run the Git Merge command separately.

In summary, Git Pull is a combination of Git Fetch and Git Merge and is used when a developer wants to update the local repository with the latest changes from the remote repository, and also wants to merge these changes with the current working branch. Git Fetch is only used to update the local repository, and the developer has to manually merge the changes with the Git Merge command.

Differences Between Pull Requests and Branches

Branch

and Pull Request are two important concepts in version control systems like Git, which allow collaboration between multiple developers working on the same codebase. The main differences between the two are as follows:

1. A branch is simply a copy of the codebase that allows developers to work on a new feature or bug fix without affecting the main codebase. Developers can create their own branches to work on separate features simultaneously.

2. A pull request, on the other hand, is a request by a developer to merge their changes from their branch into the main codebase. The pull request includes a summary of the changes made and is reviewed by other developers before being merged.

3. Branches can be used for any purpose, while pull requests are specifically designed to review and merge changes.

4. In summary, branches are used for development and experimentation, while pull requests are used for code review and merging changes into the main codebase.

Why is it called "Pull Request" instead of "Push Request" in Git?

In Git, a "Pull Request" is when a developer requests that changes made in their branch be merged into the main branch. This terminology is used because the main branch is "pulling" the changes from the developer's branch.

On the other hand, a "Push Request" would suggest that the developer is pushing their changes directly to the main branch, which is not the case in git workflow.

Therefore, the term "Pull Request" makes more sense in the context of Git's workflow and terminology.

Understanding the Difference between Git and GitHub

Git is a distributed version control system that allows developers to keep track of changes made to their code. It is a command-line tool used for tracking changes and versions of code locally.

On the other hand, GitHub is a web-based platform that hosts Git repositories in the cloud. This platform allows multiple developers to collaborate on a project by storing their code and using Git to manage changes.

In summary, while Git is a tool used for version control, GitHub is a cloud-based platform that utilizes Git to facilitate collaboration on code projects.

Overview of Git Diff and Git Status commands

The git diff command displays the differences between the working directory and the staging area. It shows the changes made to the files that are not yet staged or committed. This can be useful to verify the changes you have made.

The git status command shows the current status of your repository. It displays information on the files that have changes, have been added to the staging area, or are ready to be committed. It also shows the branch you are on and any untracked files that need to be added.

//To use git diff: git diff //This will show the changes made since the last commit.

//To use git status: git status //This will show the current status of your repository. //It will show which files have been modified and which files need to be staged or committed.

Squashing Multiple Commits into a Single Commit

To squash multiple commits into a single commit, you can use the interactive rebase feature of Git by running the following command:


git rebase -i HEAD~n

In this command, replace "n" with the number of commits you want to squash. For example, if you want to squash the last three commits into a single commit, run:


git rebase -i HEAD~3

This command will open an interactive rebase text editor, where you can choose which commits to squash and which commit message to keep. Once you have finished editing, save and close the editor, and Git will squash the selected commits into a single commit.

Recovering a Deleted Branch

If a branch has already been pushed to the central repository but has been accidentally deleted from every team member's local machines, you can still recover it.

1. First, find the commit hash that was at the tip of the deleted branch. You can do this by looking at the commit history in the central repository or by asking a team member who had the branch on their local machine.

2. Once you have the commit hash, create a new branch at that commit with the following command:

`git branch `

Replace `` with the name of the new branch you want to create and `` with the commit hash you found in step 1.

3. Finally, push the new branch to the central repository with the following command:

`git push -u origin `

Now the deleted branch has been recovered and is available to all team members again.

Git Reflog

Git reflog is a Git command that records every update made to the head or the branch reference in the git repository, including when the head reference is updated. It can help you recover lost commits or branches if necessary by providing a log of the movements of the Git Head.

Commit Object Composition

In Git, a commit object consists of several components, including the commit message, the author and committer information, the tree object representing the state of your code at the time of the commit, and zero or more parent commit objects that the new commit references. All of these components are saved as text in a special file format within the Git repository.

Understanding Git Config Levels and Configuration Values

Git config levels allow you to define configuration values for different scopes. There are three levels to consider when setting configuration values in Git:

  1. System Level - Applies to all users of the system and values are stored in the /etc/gitconfig file.
  2. User Level - Applies to a specific user and values are stored in the ~/.gitconfig or ~/.config/git/config file.
  3. Repository Level - Applies to a specific repository and values are stored in the .git/config file within the repository directory.

To configure values using these levels, you can use the `git config` command with the appropriate scope flag, followed by the configuration key and value. For example, to set a user-level value for your email address, you can use the following command:

git config --global user.email "[email protected]"

The `--global` flag specifies that the value should be set at the user level, and the `user.email` key specifies the configuration option that you want to set. Similarly, to set a repository-level value for the same configuration option within a specific repository, you can omit the `--global` flag:

git config user.email "[email protected]"

By understanding Git config levels and how to configure values using them, you can effectively manage your Git configurations as per your requirements.

Understanding Detached HEAD in Git and How to Avoid It

In Git, "HEAD" is a pointer to the current branch or commit. When you checkout a particular branch, Git moves HEAD to that branch and makes it the current working branch. However, sometimes you might find yourself in a "detached HEAD" state, meaning that you have checked out a specific commit rather than a branch, and your HEAD is no longer pointing to a branch.

A detached HEAD state can occur when you:

- Checkout a specific commit hash - Checkout a tag - Checkout a remote branch - Perform a git reset

To avoid finding yourself in a detached HEAD state, make sure to always checkout a branch instead of a specific commit or tag. If you do need to access a specific commit or tag, it's best to create a new branch before checking it out so that you can work on that branch without losing the current branch's HEAD reference.

If you accidentally end up in a detached HEAD state, don't worry. You can always create a new branch from the current commit to save your work, or simply checkout the desired branch to bring your HEAD pointer back to a branch.

Explanation of the Git Annotate Command

The Git Annotate command, also known as the Git Blame command, is used to display the author and revision information for each line in a file. This command is particularly useful for identifying who made a specific change to a file at a specific line, and can help with identifying the reasons behind those changes. The output of the Git Annotate command includes the hash of the commit, the author of that commit, the date and time the commit was made, and the specific line that was changed. This command can be executed by typing `git annotate ` or `git blame ` in the terminal, and the results will be displayed in the format `hash (author date time) line`.

Git Stash Apply vs Git Stash Pop: What's the Difference?

Both Git Stash Apply and Git Stash Pop are Git commands used to retrieve the changes that were previously stashed using the Git Stash command. However, there is a crucial difference between these two commands.

  • Git Stash Apply: This command applies the stashed changes to the current branch but keeps the stash intact. This means that in case you need them again, you can use the same stash or apply them later.
  • Git Stash Pop: This command applies the stashed changes to the current branch and removes the changes from the stash. In other words, once you use Git Stash Pop, the stored changes will be deleted permanently.

Therefore, if you are unsure whether you will need the stashed changes again, use Git Stash Apply to avoid losing them. On the other hand, if you are confident that you will not need the stashed changes again and want to remove them from the stash, use Git Stash Pop.

Advanced Git Interview Questions

One of the common advanced Git interview questions is:

What command can be used to display the list of branches that have been merged into the master branch?

The answer to this question is:

git branch --merged master

This command lists all the branches that have been merged into the master branch.

How to Resolve Conflicts in Git?

When working in a team or on a collaborative project, conflicts may arise when multiple contributors work on the same file simultaneously. Below are the steps to resolve conflicts in Git:

Step 1:

First, commit the changes you have made to your local branch by executing the command

git add.

and

git commit -m “your message”

.

Step 2:

Then, execute the command

git fetch origin

to ensure that your local repository is up-to-date with the remote repository.

Step 3:

Next, execute the command

git merge origin/master

to merge the changes from the remote repository to your local branch. If there are any conflicts, Git will notify you of them.

Step 4:

Edit the files that are in conflict to resolve them. You can use any code editor or Git’s built-in mergetool to resolve the conflicts. Save the changes once you have made the necessary modifications.

Step 5:

Once you have resolved the conflicts, execute the command

git add.

to add the resolved files to the staging area.

Step 6:

Finally, execute the command

git commit -m “resolve conflict”

to commit the resolved changes to your local branch. Push the changes to the remote repository by executing the command

git push origin your-branch-name

.

By following these steps, you can effectively resolve conflicts in Git and ensure that your changes are successfully merged with the remote repository.

What is the best course of action for a broken commit: creating an additional commit or amending an existing commit?

When facing a broken commit, the best practice is to amend the existing commit rather than creating a new one. This ensures that the commit history remains clean and organized. However, if the changes are significant and cannot be amended easily, creating an additional commit may be necessary. It's important to communicate with your team members and follow the version control guidelines in place.

Reverting a Bad Commit That Has Already Been Pushed

If you have made a bad commit and have already pushed it, you can use the "git revert" command to undo the changes made by that commit. First, identify the commit SHA (hash) that you want to revert using "git log". Once you have the SHA, run the command "git revert " to create a new commit that undoes the changes made by the bad commit. This new commit will be added to the history and can be pushed to the remote repository. It's important to note that this command creates a new commit rather than modifying the existing one, so the bad commit will still be in the history but will be effectively neutralized by the new revert commit.

git log //identify the SHA of the bad commit 
git revert <SHA> //create a new commit that undoes the changes made by the bad commit 

Explanation of the "git cherry-pick" command

The "git cherry-pick" command is a feature provided by Git that allows a developer to select one or more commits from a branch, and apply them to another branch. This command helps in transferring specific changes without having to merge the entire branch. It is useful in case a developer needs to add a bugfix or a new feature to one branch, but does not want all the changes from the other branch. This command creates a new commit with a new hash, which has the changes from the cherry-picked commit.

For example, if a commit from branch "A" needs to be applied to branch "B", the developer can use "git cherry-pick" to select that commit, and apply it to the "B" branch. This helps in maintaining the codebase, and in the efficient management of code changes.

Steps to Remove a File from Git Index without Removing from the Local File System

When you remove a file from the Git index, it will no longer be tracked, but it will remain in the local file system. Here are the steps to do so:

  1. Open the terminal and navigate to the Git repository where the file is located.
  2. Enter the command:
    git rm --cached file-name

    . This will remove the file from the Git index.

  3. Commit the changes by entering the command:
    git commit -m "Removed file from Git index"

    .

Now, the file will no longer be tracked by Git, but it will remain in the local file system.

Factors to Consider When Choosing Between Git Merge and Git Rebase

When deciding between Git merge and Git rebase command, there are several factors to consider. Here are some of them:

1. Workflow: Opt for Git merge if you want to keep a linear history of your commits, or Git rebase if you want to have a clean, linear history of your changes.

2. Collaboration: If you are working on a public repository with other developers, it may be safer to use Git merge, as it preserves each developer's unique contributions. On the other hand, if you are working on a local repository with a few contributors, Git rebase can be a useful way to streamline and simplify your history.

3. Commit frequency: When multiple commits are made in a short period, Git merge can be a better option, as it combines all changes at once. For less frequent, more significant changes, Git rebase may be the better choice.

4. Risk tolerance: Consider the risk involved, as Git rebase can sometimes cause conflicts to arise. If you are not comfortable resolving merge conflicts manually, Git merge may be a better option.

In summary, it's essential to weigh the pros and cons of each command depending on your workflow, collaboration style, commit frequency, and risk tolerance.

Finding a Commit that Broke Something after a Merge Operation

In order to find a commit that caused an issue after a merge operation, you can follow these steps:

  1. Identify the last commit that worked correctly by checking out the code at a previous commit and verifying that the code was functioning correctly.
  2. Checkout the merge commit that you suspect caused the issue by running
    git checkout [merge commit hash]

    .

  3. Run the code and verify that it is failing as expected.
  4. Use the
    git bisect

    command to find the commit that introduced the issue. The

    git bisect

    command allows you to perform a binary search to find the faulty commit by marking a commit as good or bad and then automatically checking out the middle commit between the two.

  5. Mark the current commit as bad by running
    git bisect bad

    .

  6. Mark the commit that you know was working correctly as good by running
    git bisect good [good commit hash]

    .

  7. Git will check out a new commit in the middle of the range. Verify if the code works correctly or not.
  8. If the code works correctly, mark this commit as good by running
    git bisect good

    .

  9. If the code is still broken, mark this commit as bad by running
    git bisect bad

    .

  10. Keep repeating steps 7-9 until Git finds the first faulty commit in the range.

Once you have found the faulty commit, you can use Git tools like

git show

to investigate what went wrong and to determine an appropriate fix.

Functionalities of git reset --mixed and git merge --abort

Git is a popular version control system that allows developers to make changes to their codebase without sacrificing previous versions. Two useful features of Git are "git reset --mixed" and "git merge --abort".

git reset --mixed allows a developer to undo changes to a specific commit without deleting the commit itself. This means that the developer can modify the code without losing previous versions. By using this command, the developer can reset a branch to a previous commit while keeping the changes in the working directory.

git merge --abort lets a developer abandon a merge in progress. Sometimes, when merging branches, things can go wrong, and the merge process may fail. If it happens, the developer can use "git merge --abort" to abort the merge and return the code to the state it was in before the merge process started.

By mastering these two functions, developers can achieve better control over their codebase, manage their repositories more efficiently, and optimize their development process.

Differences between Git Revert and Git Reset

When working with git, it is important to understand the differences between the commands Git Revert and Git Reset.

Git Revert is used to create a new commit that undoes one or more previous commits. It does this by creating a new commit with changes that are the opposite of the ones that were made in the previous commit(s). This allows the undoing of changes without deleting commit history. Git Revert is best used when changes have already been pushed to a public branch.

Git Reset, on the other hand, is used to undo changes by rewinding the repository to a previous commit. It does this by resetting the HEAD and changing the branch to a previous commit. This means that any commits made after the reset point will be discarded. Git Reset is best used when changes have not yet been pushed to a public branch.

In summary, Git Revert is used to undo changes without deleting commit history, while Git Reset is best used when changes need to be completely removed, without the need for commit history.

Conclusion

The conclusion section of a written work serves to summarize and tie together the main points, insights or arguments that were presented. In academic papers, this section is usually written at the end, but in other types of works (such as novels), the conclusion may come at any point in the narrative. Regardless of the context, the conclusion plays a crucial role in providing closure to the reader or audience.

//sample code here

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.