0% found this document useful (0 votes)
245 views24 pages

GIT Interview Questions

The document discusses various Git commands - reset, rebase, pull and checkout. It explains that reset works on the local repository without touching commits, while rebase rewrites commit objects. Pull does a fetch followed by a merge to update local branches. Merge combines branches, rebase replays commits as if based on another parent for history cleanup, and reset undoes changes or commits.

Uploaded by

mail sr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
245 views24 pages

GIT Interview Questions

The document discusses various Git commands - reset, rebase, pull and checkout. It explains that reset works on the local repository without touching commits, while rebase rewrites commit objects. Pull does a fetch followed by a merge to update local branches. Merge combines branches, rebase replays commits as if based on another parent for history cleanup, and reset undoes changes or commits.

Uploaded by

mail sr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

git-reset works with refs, on your working directory and the index, without

touching any commit objects (or other objects). git-rebase on the other hand
is used to rewrite previously made commit objects. ... In general having such
commits in the history is perfectly fine.

In the simplest terms, git pull does a git fetch followed by a git merge. You
can do a git fetch at any time to update your remote-tracking branches
under refs/remotes/<remote>/. This operation never changes any of your
own local branches under refs/heads, and is safe to do without changing
your working copy

Merge

 merges together different branches (different histories, to be more exact)


 fast-forwards if a merge isn't necessary; effectively repositioning the branch head to
a descendant commit
 unwanted outcome of git pull

Rebase

 replays a set of commits as if they were based off another parent


 interactively used for history cleanup: reorder & squash related commits
 should be used for git pull instead of merge

Reset

 resets (unstages) changes added to the index; undoes git add


 repositions the branch head to another commit; optionally resetting index &
working tree
o undo a commit, either discarding changes or keeping them for the next
commit
o discard all working copy changes since the last commit

Checkout

 switch branches
o create a new branch and switch to it
 checkout a file or directory as it were in another commit
o discard all working copy changes since the last commit
o resolve merge conflicts

Difference between git reset soft, mixed and


hard
The reset command. Confusing. Misunderstood.
Misused. But it doesn’t need to be that way! It’s really
not too confusing once you figure out what’s going on.
Definitions
First, let’s define a few terms.

HEAD

This is an alias for the tip of the current branch, which is the most
recent commit you have made to that branch.

Index

The index, also known as the staging area, is the set of files that will
become the next commit. It is also the commit that will
become HEAD’s parent.
Working Copy

This is the term for the current set of files you’re working on in
your file system.

Flow
When you first checkout a branch, HEAD points to the most recent
commit in the branch. The files in the HEAD (they aren’t
technically files, they’re blobs but for the purposes of this
discussion we can think of them as straight files) match that of the
files in the index, and the files checked out in your working copy
match HEAD and the index as well. All 3 are in an equal state, and
Git is happy.

When you perform a modification to a file, Git notices and says


“oh, hey, something has changed. Your working copy no longer
matches the index and HEAD.” So it marks the file as changed.
Then, when you do a git add, it stages the file in the index, and Git
says “oh, okay, now your working copy and index match, but those
are both different than HEAD.”
When you then perform a git commit, Git creates a new commit
that HEAD now points to and the status of the index and working
copy match it so Git’s happy once more.
Reset
If you just look at the reset command by itself, all it does is reset
HEAD (the tip of the current branch) to another commit. For
instance, say we have a branch (the name doesn’t matter, so let’s
call this one “super-duper-feature”) and it looks like so:

If we perform:
> git reset HEAD
… nothing happens. This is because we tell git to reset this branch
to HEAD, which is where it already is. But if we do:
> git reset HEAD~1
(HEAD~1 is shorthand case for “the commit right before HEAD”,
or put differently “HEAD’s parent”) our branch now looks like so:

If we start at the latest commit again and do:


> git reset HEAD~2
our branch would look like so:

Again, all it does on a basic level is move HEAD to another


commit.
Parameters
So the reset command itself is pretty simple, but it’s the parameters
that cause confusion. The main parameters
are soft, hard and mixed. These tell Git what to do with your index
and working copy when performing the reset.
Soft

The --soft parameter tells Git to reset HEAD to another commit,


but that’s it. If you specify --soft Git will stop there and nothing
else will change. What this means is that the index and working
copy don’t get touched, so all of the files that changed between the
original HEAD and the commit you reset to appear to be staged.

Mixed (default)

The --mixed parameter (which is the default if you don’t specify


anything) will reset HEAD to another commit, and will reset the
index to match it, but will stop there. The working copy will not be
touched. So, all of the changes between the original HEAD and the
commit you reset to are still in the working copy and appear as
modified, but not staged.

Hard

The --hard parameter will blow out everything – it resets HEAD


back to another commit, resets the index to match it, and resets the
working copy to match it as well. This is the more dangerous of the
commands and is where you can cause damage. Data might get lost
here*!
 You can recover it using git reflog but that’s out of scope here.

Q1. What is Git?

I will suggest you to attempt this question by first telling about the architecture of git as
shown in the below diagram just try to explain the diagram by saying:

Git is a Distributed Version Control system (DVCS). It can track changes to a file and allows
you to revert back to any particular change.

Its distributed architecture provides many advantages over other Version Control Systems
(VCS) like SVN one major advantage is that it does not rely on a central server to store all
the versions of a project’s files. Instead, every developer “clones” a copy of a repository I
have shown in the diagram with “Local repository” and has the full history of the project on
his hard drive so when there is a server outage all you need for recovery is one of your
teammate’s local Git repository. There is a central cloud repository as well where
developers can commit changes and share it with other teammates as you can see in the
diagram where all collaborators are commiting changes “Remote repository”.
Now remember, you have mentioned SVN in the previous answer, so the next question in this
Git Interview Questions blog will be related to the difference between Git and SVN

Q2. What is the difference between Git and SVN?

The proper answer for this according to me will be the architectural differences between Git
and SVN. So the basic difference is that Git is distributed and SVN is centralized version
control system.

Then explain the same by including the below mentioned differences:

Now, the next set of Git interview questions will test your experience with Git:

Q3. What is the command to write a commit message in Git?

Answer to this is pretty straightforward.

Command that is used to write a commit message is “git commit -a”.

Now explain about -a flag by saying -a on the command line instructs git to commit the new
content of all tracked files that have been modified. Also mention you can use “git
add<file>” before git commit -a if new files need to be committed for the first time.

Q4. What is ‘bare repository’ in Git?

You are expected to tell the difference between a “working directory” and “bare
repository”.

A “bare” repository in Git just contains the version control information and no working files
(no tree) and it doesn’t contain the special .git sub-directory. Instead, it contains all the
contents of the .git sub-directory directly in the main directory itself, where as working
directory consist of:

1. A .git subdirectory with all the Git related revision history of your repo.

2. A working tree, or checked out copies of your project files.


Q5. What language is used in Git?

Instead of just telling the name of the language, you need to tell the reason for using it as
well. I will suggest you to answer this by saying:

Git uses ‘C’ language. GIT is fast, and ‘C’ language makes this possible by reducing the
overhead of run times associated with high level languages.

Q6. In Git how do you revert a commit that has already been pushed and made public?

There can be two answers to this question and make sure that you include both because
any of the below options can be used depending on the situation:

 Remove or fix the bad file in a new commit and push it to the remote repository. This
is the most natural way to fix an error. Once you have made necessary changes to
the file, commit it to the remote repository for that I will use
git commit -m “commit message”

 Create a new commit that undoes all changes that were made in the bad commit.to
do this I will use a command
git revert <name of bad commit>

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

Git pull command pulls new changes or commits from a particular branch from your central
repository and updates your target branch in your local repository.

Git fetch is also used for the same purpose but it works in a slightly different way. When you
perform a git fetch, it pulls all new commits from the desired branch and stores it in a new
branch in your local repository. If you want to reflect these changes in your target branch,
git fetch must be followed with a git merge. Your target branch will only be updated after
merging the target branch and fetched branch. Just to make it easy for you, remember the
equation below:

Git pull = git fetch + git merge

Q8. What is ‘staging area’ or ‘index’ in Git?

For this answer try to explain the below diagram as you can see:

That before completing the commits, it can be formatted and reviewed in an intermediate
area known as ‘Staging Area’ or ‘Index’. From the diagram it is evident that every change is
first verified in the staging area I have termed it as “stage file” and then that change is
committed to the repository.

If your interviewer has good knowledge on Git he/she will dig in deep, so the next set of Git
interview questions will be more challenging.

Q9. What is Git stash?

According to me you should first explain the need for Git stash.

Often, when you’ve been working on part of your project, things are in a messy state and
you want to switch branches for sometime to work on something else. The problem is, you
don’t want to do a commit of half-done work just so you can get back to this point later. The
answer to this issue is Git stash.

Now explain what is Git stash.

Stashing takes your working directory that is, your modified tracked files and staged
changes and saves it on a stack of unfinished changes that you can reapply at any time.

Q10. What is Git stash drop?

Begin this answer by saying for what purpose we use Git ‘stash drop’.

Git ‘stash drop’ command is used to remove the stashed item. It will remove the last added
stash item by default, and it can also remove a specific item if you include it as an argument.

Now give an example.

If you want to remove a particular stash item from the list of stashed items you can use the
below commands:

git stash list: It will display the list of stashed items like:
stash@{0}: WIP on master: 049d078 added the index file
stash@{1}: WIP on master: c264051 Revert “added file_size”
stash@{2}: WIP on master: 21d80a5 added number to log

If you want to remove an item named stash@{0} use command git stash drop stash@{0}.

Q11. How do you find a list of files that has changed in a particular commit?

For this answer instead of just telling the command, explain what exactly this command will
do.

To get a list files that has changed in a particular commit use the below command:

git diff-tree -r {hash}

Given the commit hash, this will list all the files that were changed or added in that commit.
The -r flag makes the command list individual files, rather than collapsing them into root
directory names only.

You can also include the below mentioned point, although it is totally optional but will help
in impressing the interviewer.

The output will also include some extra information, which can be easily suppressed by
including two flags:

git diff-tree –no-commit-id –name-only -r {hash}


Here –no-commit-id will suppress the commit hashes from appearing in the output, and –
name-only will only print the file names, instead of their paths.

Q12. What is the function of ‘git config’?

First tell why we need ‘git config‘.


Git uses your username to associate commits with an identity. The git config command can
be used to change your Git configuration, including your username.
Now explain with an example.
Suppose you want to give a username and email id to associate commit with an identity so
that you can know who has made a particular commit. For that I will use:
git config –global user.name “Your Name”: This command will add username.
git config –global user.email “Your E-mail Address”: This command will add email id.

Q13. What does commit object contains?

Commit object contains the following components; you should mention all the three points
present below:
 A set of files, representing the state of a project at a given point of time
 Reference to parent commit objects
 An SHAI name, a 40 character string that uniquely identifies the commit object.
Q14. How can you create a repository in Git?
This is probably the most frequently asked questions and answer to this is really simple.
To create a repository, create a directory for the project if it does not exist, then run
command “git init”. By running this command .git directory will be created in the project
directory.
Q15. How do you squash last N commits into a single commit?
There are two options to squash last N commits into a single commit include both of the
below mentioned options in your answer:
 If you want to write the new commit message from scratch use the following
command
git reset –soft HEAD~N &&
git commit
 If you want to start editing the new commit message with a concatenation of the
existing commit messages then you need to extract those messages and pass them
to Git commit for that I will use
git reset –soft HEAD~N &&
git commit –edit -m”$(git log –format=%B –reverse .HEAD@{N})”
Q16. What is Git bisect? How can you use it to determine the source of a (regression) bug?
I will suggest you to first give a small definition of Git bisect.
Git bisect is used to find the commit that introduced a bug by using binary search.
Command for Git bisect is
git bisect <subcommand> <options>
Now since you have mentioned the command above explain them what this command will
do.
This command uses a binary search algorithm to find which commit in your project’s history
introduced a bug. You use it by first telling it a “bad” commit that is known to contain the
bug, and a “good” commit that is known to be before the bug was introduced. Then Git
bisect picks a commit between those two endpoints and asks you whether the selected
commit is “good” or “bad”. It continues narrowing down the range until it finds the exact
commit that introduced the change.
Q17. How do you configure a Git repository to run code sanity checking tools right before
making commits, and preventing them if the test fails?
I will suggest you to first give a small introduction to sanity checking.
A sanity or smoke test determines whether it is possible and reasonable to continue testing.
Now explain how to achieve this.
This can be done with a simple script related to the pre-commit hook of the repository.
The pre-commit hook is triggered right before a commit is made, even before you are
required to enter a commit message. In this script one can run other tools, such as linters
and perform sanity checks on the changes being committed into the repository.
Finally, give an example, you can refer the below script:
#!/bin/sh
files=$(git diff –cached –name-only –diff-filter=ACM | grep ‘.go$’)
if [ -z files ]; then
exit 0
fi
unfmtd=$(gofmt -l $files)
if [ -z unfmtd ]; then
exit 0
fi
echo “Some .go files are not fmt’d”
exit 1
This script checks to see if any .go file that is about to be committed needs to be passed
through the standard Go source code formatting tool gofmt. By exiting with a non-zero
status, the script effectively prevents the commit from being applied to the repository.
The Interviewer has not started asking questions on branching yet, so the next set of Git
interview questions will be dealing with branching in Git.
Q18. Describe branching strategies you have used?
This question is asked to test your branching experience with Git so, tell them about how
you have used branching in your previous job and what purpose does it serves, you can
refer the below mention points:
 Feature branching
A feature branch model keeps all of the changes for a particular feature inside of a
branch. When the feature is fully tested and validated by automated tests, the
branch is then merged into master.
 Task branching
In this model each task is implemented on its own branch with the task key
included in the branch name. It is easy to see which code implements which task,
just look for the task key in the branch name.
 Release branching
Once the develop branch has acquired enough features for a release, you can clone
that branch to form a Release branch. Creating this branch starts the next release
cycle, so no new features can be added after this point, only bug fixes,
documentation generation, and other release-oriented tasks should go in this
branch. Once it is ready to ship, the release gets merged into master and tagged
with a version number. In addition, it should be merged back into develop branch,
which may have progressed since the release was initiated.
In the end tell them that branching strategies varies from one organization to another so I
know basic branching operations like delete, merge, checking out a branch etc..
Q19. How will you know in Git if a branch has already been merged into master?
The answer is pretty direct.
To know if a branch has been merged into master or not you can use the below commands:
git branch –merged It lists the branches that have been merged into the current branch.
git branch –no-merged It lists the branches that have not been merged.
Q20. What is Git rebase and how can it be used to resolve conflicts in a feature branch
before merge?
According to me you should start by saying git rebase is a command which will merge
another branch into the branch where you are currently working, and move all of the local
commits that are ahead of the rebased branch to the top of the history on that branch.
Now, once you have defined Git rebase time for an example to show how it can be used to
resolve conflicts in a feature branch before merge.
If a feature branch was created from the master, and since then the master branch has
received new commits, Git rebase can be used to move the feature branch to the tip of
master. The command effectively will replay the changes made in the feature branch at
the tip of master, allowing conflicts to be resolved in the process. When done with care,
this will allow the feature branch to be merged into master with relative ease and
sometimes as a simple fast-forward operation.
You can also expect some off track questions, so the next question in this Git interview
questions blog will be regarding SubGit.
Q21. What is SubGit?
Begin this answer by explaining what is SubGit used for.
SubGit is a tool for SVN to Git migration. It creates a writable Git mirror of a local or
remote Subversion repository and uses both Subversion and Git as long as you like.
Now you can include some advantages like you can do a fast one-time import from
Subversion to Git or use SubGit within Atlassian Bitbucket Server.We can use SubGit to
create a bi-directional Git-SVN mirror of existing Subversion repository. You can push to Git
or commit to Subversion at your convenience. Synchronization will be done by SubGit.
Git Interview Questions : javapedia
Difference between git commit and git push command.
git commit records changes to the local repository while git push updates the changes to
the remote repository and the changes be visible to the other users.

Difference between git pull and fetch.


Git fetch gathers any commits from the target branch that do not exist in your current
branch and stores them in your local repository. However, it does not merge them with
your current branch.
Git pull update your current HEAD branch with the latest changes from the remote server.
This means that pull not only downloads new data and also directly integrates it into your
current working copy files.
Difference between git stash apply and git stash pop.
git stash pop removes the stash (topmost) after applying it, whereas git stash apply leaves it
in the stash list for possible later reuse.
git stash pop is equivalent to git stash apply and git stash drop.
What is GIT?
GIT is a distributed version control system and source code management (SCM) system with
an emphasis to handle small and large projects with speed and efficiency.
Git is a free and open source.
Main difference between Git and SVN.
Git is a distributed version control system (DVCS), while SVN is a centralized version control
system.
Advantages of GIT.
Distributed Development: In SVN, each developer gets a working copy that points back to a
single central repository. Git, however, is a distributed version control system. Instead of a
working copy, each developer gets their own local repository, complete with a full history of
commits.
Free and open source.
Easier branching.
High availability.
Faciliates team collaboration.
What is version control?
Version control systems are a type of software tools that help software developers manage
his changes to source code over time. Version control software keeps track of every
modification to the code in a special kind of database. Developers can turn back the clock if
necessary and compare earlier versions of the code to help fix the mistake while minimizing
disruption to all team members.
What is a repository in GIT?
Git stores project details and files information in a data structure called a repository. The Git
repository is stored in the same directory as the project itself, in a subdirectory called .git.
A git repository contains, among other things, the following:
 A set of commit objects.
 A set of references to commit objects, called heads.
What is a bare Git repository?
A bare Git repository is a repository that is created without a Working Tree.
git init --bare
What is an Index in GIT?
The index is a single, large, binary file in under .git folder, which lists all files in the current
branch, their sha1 checksums, time stamps and the file name.
Before completing the commits, it is formatted and reviewed in an intermediate area
known as Index also known as the staging area.
GIT Lifecycle.
What language(s) is used in Git?
The core Git distribution is written in C and (Bourne) shell scripts and also using Perl.
Difference between git fetch and git pull.
git fetch imports commits from a remote repository into your local repo. If you want to
reflect these changes in your target branch, git fetch must be followed with a git merge.
Since fetched content is represented as a remote branch, it has absolutely no effect on your
local development work. This makes fetching a safe way to review commits before
integrating them with your local repository. Your target branch will only be updated after
merging the target branch and fetched branch.
git pull does a git fetch followed by a git merge. 'git pull' downloads as well as merges the
data from a remote repository into your local working files. It may also lead to merge
conflicts if your local changes are not yet committed.
git pull = git fetch + git merge
What do you mean by git add?
‘git add .’ command adds all modified and new files in the current directory and all
subdirectories to the staging area (index), thus preparing them to be included in the next
git commit. Any files matching the patterns in the .got ignore file will be ignored by git add.
What is the difference between git init and git init --bare?
Non-Bare variant creates a repository with a working directory so you can actually work.
The bare git init creates a repository without a working directory.Bare repositories are
usually central repositories where everyone moves their work to.
What does the 'git reset' command do?
'Git Reset' resets your index as well as the working directory to the state of your last
commit.
What is Git stash?
git stash temporarily shelves (or stashes) changes you have made to your working copy so
you can work on something else, and then come back and re-apply them later on.
Explain git status command.
The git status command displays the state of the working directory and the staging area. It
lets you see which changes have been staged, which haven’t, and which files aren’t being
tracked by Git.
Can we create multiple stashes?
Yes. You can run git stash several times to create multiple stashes, and then use git stash
list to view them.
Explain git revert command.
The git revert command is used for undoing changes to a repository's commit history. Git
revert expects a commit ref passed in. To revert the latest commit use git revert HEAD
command.
git revert simply creates a new commit that is the opposite of an existing commit. So a git
push need to be followed to update in remote repository.
Difference between git commit and git push.
The git commit records changes to the repository while git push updates remote refs along
with associated object.
git commit record your changes to the local repository. git push update the remote
repository with your local committed changes.
How to view the commit history in git?
git log command lists the commits made in that repository in reverse chronological so that
most recent commits show up first.

Git Interview Questions (mindmajix)


According to research Git has a market share of about 68%. So, You still have opportunity to
move ahead in your career in Git Development. Mindmajix offers Advanced Git Interview
Questions 2018 that helps you in cracking your interview & acquire dream career as Git
Developer.
Q. What are the best graphical GIT client in LINUX?
1. Git Cola
2. Git-g
3. Smart git
4. Giggle
5. Git GUI
6. qGit
Q. How do you revert a commit that has already been pushed and made public?
One or more commits can be reverted through the use of git revert. This command, in
essence, creates a new commit with patches that cancel out the changes introduced in
specific commits. In case the commit that needs to be reverted has already been published
or changing the repository history is not an option, git revert can be used to revert commits.
Running the following command will revert the last two commits:
git revert HEAD~2..HEAD
Alternatively, one can always checkout the state of a particular commit from the past, and
commit it anew.
Q. How do you squash last N commits into a single commit?
Squashing multiple commits into a single commit will overwrite history, and should be done
with caution. However, this is useful when working in feature branches. To squash the last N
commits of the branch currently on, run the following command (with {N} replaced with the
number of commits that you want to squash):
git rebase -i HEAD~{N}
Upon running this command, an editor will open with a list of these N commit messages,
one per line. Each of these lines will begin with the word “pick”. Replacing “pick” with
“squash” or “s” will tell Git to combine the commit with the commit before it. To combine
all N commits into one, set every commit in the list to be squash except the first one. Upon
exiting the editor, and if no conflict arises, git rebase will allow you to create a new commit
message for the new combined commit.
Q. How do you find a list of files that has changed in a particular commit?
git diff-tree -r {hash}
Given the commit hash, this will list all the files that were changed or added in that commit.
The -r flag makes the command list individual files, rather than collapsing them into root
directory names only.
The output will also include some extra information, which can be easily suppressed by
including a couple of flags:
git diff-tree –no-commit-id –name-only -r {hash}
Here –no-commit-id will supress the commit hashes from appearing in the output, and –
name-only will only print the file names, instead of their paths.
Q. How do you setup a script to run every time a repository receives new commits through
push?
To configure a script to run every time a repository receives new commits through push,
one needs to define either a pre-receive, update, or a post-receive hook depending on when
exactly the script needs to be triggered.
Pre-receive hook in the destination repository is invoked when commits are pushed to it.
Any script bound to this hook will be executed before any references are updated. This is a
useful hook to run scripts that help enforce development policies.
Update hook works in a similar manner to pre-receive hook, and is also triggered before any
updates are actually made. However, the update hook is called once for every git-commit
that have pushed to the destination repository.
Finally, post-receive hook in the repository is invoked after the updates have been accepted
into the destination repository. This is an ideal place to configure simple deployment scripts,
invoke some continuous integration systems, dispatch notification emails to repository
maintainers, etc.
Hooks are local to every Git repository and are not versioned. Scripts can either be created
within the hooks directory inside the “.git” directory, or they can be created elsewhere and
links to those scripts can be placed within the directory.
Q. What is git bisect? How can you use it to determine the source of a (regression) bug?
Git provides a rather efficient mechanism to find bad commits. Instead of making the user
try out every single commit to find out the first one that introduced some particular issue
into the code, git bisect allows the user to perform a sort of binary search on the entire
history of a repository.
By issuing the git-command bisect start, the repository enters bisect mode. After this, all
you have to do is identify a bad and a good commit:
git bisect bad # marks the current version as bad
git bisect good {hash or tag} # marks the given hash or tag as good, ideally of some earlier
commit
Once this is done, Git will then have a range of commits that it needs to explore. At every
step, it will checkout a certain commit from this range, and require you to identify it as good
or bad. After which the range will be effectively halved, and the whole search will require a
lot less number of steps than the actual number of commits involved in the range. Once the
first bad commit has been found, or the bisect mode needs to be ended, the following
command can be used to exit the mode and reset the bisection state:
git bisect reset
Q. What are the different ways you can refer to a commit?
In Git each commit is given a unique hash. These hashes can be used to identify the
corresponding commits in various scenarios (such as while trying to checkout a particular
state of the code using the git checkout {hash} command).
Additionally, Git also maintains a number of aliases to certain commits, known as refs.
Also, every tag that you create in the repository effectively becomes a ref (and that is
exactly why you can use tags instead of commit hashes in various git plumbing
commands). Git also maintains a number of special aliases that change based on the state
of the repository, such as HEAD, FETCH_HEAD, MERGE_HEAD, etc.
Git also allows commits to be referred as relative to one another. For example, HEAD~1
refers to the commit parent to HEAD, HEAD~2 refers to the grandparent of HEAD, and so
on. In case of merge commits, where the commit has two parents, ^ can be used to select
one of the two parents, e.g. HEAD^2 can be used to follow the second parent.
And finally, refspecs. These are used to map local and remote branches together. However,
these can be used to refer to commits that reside on remote branches allowing one to
control and manipulate them from a local Git environment.
Q. What is git rebase and how can it be used to resolve conflicts in a feature branch before
merge?
In simple words, git rebase allows one to move the first commit of a branch to a new
starting location. For example, if a feature branch was created from master, and since
then the master branch has received new commits, git rebase can be used to move the
feature branch to the tip of master. The command effectively will replay the changes that
are made in the feature branch at the tip of master, allowing conflicts to be resolved in
the process. When done with care, this will allow the feature branch to be merged into
master with relative ease and sometimes as a simple fast-forward operation.
Q. How do you configure a Git repository to run code sanity checking tools right before
making commits, and preventing them if the test fails?
This can be done with a simple script bound to the pre-commit hook of the repository. The
pre-commit hook is triggered right before a commit is made, even before you are required
to enter a commit message. In this script one can run other tools, such as linters and
perform sanity checks on the changes being committed into the repository. For example,
the following script:
#!/bin/sh
files=$(git diff –cached –name-only –diff-filter=ACM | grep ‘.go$’)
if [ -z files ]; then
exit 0
fi
unfmtd=$(gofmt -l $files)
if [ -z unfmtd ]; then
exit 0
fi
echo “Some .go files are not fmt’d”
exit 1
… checks to see if any .go file that is about to be commited needs to be passed through the
standard Go source code formatting tool gofmt. By exiting with a non-zero status, the script
effectively prevents the commit from being applied to the repository.

GIT interview Question and Answers: foxutech


1. What is ‘bare repository’ in Git?

A “bare” repository in Git just contains the version control information and no working files
(no tree) and it doesn’t contain the special .git sub-directory. Instead, it contains all the
contents of the .git sub-directory directly in the main directory itself, where as working
directory consist of:

– A .git subdirectory with all the Git related revision history of your repo.
– A working tree, or checked out copies of your project files.

2. In Git how do you revert a commit that has already been pushed and made public?

There can be two answers to this question and make sure that you include both because
any of the below options can be used depending on the situation:

Remove or fix the bad file in a new commit and push it to the remote repository. This is the
most natural way to fix an error. Once you have made necessary changes to the file, commit
it to the remote repository for that I will use
# git commit -m “commit message”

Create a new commit that undoes all changes that were made in the bad commit.to do this I
will use a command
# git revert <name of bad commit>

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

Git pull command pulls new changes or commits from a particular branch from your central
repository and updates your target branch in your local repository.

Git fetch is also used for the same purpose but it works in a slightly different way. When you
perform a git fetch, it pulls all new commits from the desired branch and stores it in a new
branch in your local repository. If you want to reflect these changes in your target branch,
git fetch must be followed with a git merge. Your target branch will only be updated after
merging the target branch and fetched branch. Just to make it easy for you, remember the
equation below:
Git pull = git fetch + git merge

4. How do you find a list of files that has changed in a particular commit?

To get a list files that has changed in a particular commit use the below command:
git diff-tree -r {hash}

Given the commit hash, this will list all the files that were changed or added in that commit.
The -r flag makes the command list individual files, rather than collapsing them into root
directory names only.

You can also include the below mentioned point, although it is totally optional but will help
in impressing the interviewer.

The output will also include some extra information, which can be easily suppressed by
including two flags:
git diff-tree –no-commit-id –name-only -r {hash}

Here –no-commit-id will suppress the commit hashes from appearing in the output, and –
name-only will only print the file names, instead of their paths.

5. What does commit object contains?

Commit object contains the following components, you should mention all the three points
present below:

A set of files, representing the state of a project at a given point of time


Reference to parent commit objects
An SHAI name, a 40 character string that uniquely identifies the commit object.

6. How do you squash last N commits into a single commit?

There are two options to squash last N commits into a single commit include both of the
below mentioned options in your answer:

If you want to write the new commit message from scratch use the following command
# git reset –soft HEAD~N &&
# git commit

If you want to start editing the new commit message with a concatenation of the existing
commit messages then you need to extract those messages and pass them to Git commit for
that I will use
# git reset –soft HEAD~N &&
# git commit –edit -m”$(git log –format=%B –reverse .HEAD@{N})”
7. How do you configure a Git repository to run code sanity checking tools right before
making commits, and preventing them if the test fails?

A sanity or smoke test determines whether it is possible and reasonable to continue testing.

This can be done with a simple script related to the pre-commit hook of the repository. The
pre-commit hook is triggered right before a commit is made, even before you are required
to enter a commit message. In this script one can run other tools, such as linters and
perform sanity checks on the changes being committed into the repository.

Finally, give an example, you can refer the below script:


#!/bin/sh
files=$(git diff –cached –name-only –diff-filter=ACM | grep ‘.go$’)
if [ -z files ]; then
exit 0
fi
unfmtd=$(gofmt -l $files)
if [ -z unfmtd ]; then
exit 0
fi
echo “Some .go files are not fmt’d”
exit 1

This script checks to see if any .go file that is about to be committed needs to be passed
through the standard Go source code formatting tool gofmt. By exiting with a non-zero
status, the script effectively prevents the commit from being applied to the repository.

8.How will you know in Git if a branch has already been merged into master?

To know if a branch has been merged into master or not you can use the below commands:
git branch –merged It lists the branches that have been merged into the current branch.
git branch –no-merged It lists the branches that have not been merged.

9. What is SubGit?

SubGit is a tool for SVN to Git migration. It creates a writable Git mirror of a local or remote
Subversion repository and uses both Subversion and Git as long as you like.

Now you can include some advantages like you can do a fast one-time import from
Subversion to Git or use SubGit within Atlassian Bitbucket Server.We can use SubGit to
create a bi-directional Git-SVN mirror of existing Subversion repository. You can push to Git
or commit to Subversion at your convenience. Synchronization will be done by SubGit.

10. How do you cherry-pick a merge commit?

Cherry-pick uses a diff to find the difference between branches.


As a merge commit belongs to a different branch, it has two parents and two changesets.

For example, if you have merge commt ref 63ad84c, you have to specify -m and use parent
1 as a base:
# git checkout release_branch
# git cherry-pick -m 1 63ad84c

11. What is Git fork? What is difference between fork and branch? How to create tag?

A fork is a copy of a repository. Forking a repository allows you to freely experiment with
changes without affecting the original project.

A fork is really a Github (not Git) construct to store a clone of the repo in your user account.
As a clone, it will contain all the branches in the main repo at the time you made the fork.

Create Tag:

– Click the releases link on our repository page.


– Click on Create a new release or Draft a new release.
– Fill out the form fields, then click Publish release at the bottom.
– After you create your tag on GitHub, you might want to fetch it into your local repository
too: git fetch.

12. How to rebase master in git? Difference between rebase and merge. How to squash or
fixup commits?

Rebasing is the process of moving a branch to a new base commit.

The golden rule of git rebase is to never use it on public branches. … The only way to
synchronize the two master branches is to merge them back together, resulting in an extra
merge commit and two sets of commits that contain the same changes.

13. What Are The Advantages Of Using Git?

a) Data redundancy and replication


b) High availability
c) Only one.git directory per repository
d) Superior disk utilization and network performance
e) Collaboration friendly
f) Any sort of projects can use GIT.

You might also like