Git

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Cheat Sheet

Getting Started with Git

Working on a Project

Managing Versions of a Document

We keep making many changes when building software or even writing


anything.

Advantages of Versioning

 We can quickly revert back to any of the older versions or pick up


changes from an older version.

 We can check how the files are modified over time.

Managing Versions of a Project

When working on a software project, we keep making changes to existing


files to add new features and fix existing bugs

Collaboration

When working on a huge project with many files which is being developed
by multiple people it is hard to manually keep track of the changes.

 Any small change may completely crash the project.

Versioning

When working with multiple people, it is useful to know,

 Who made changes to a given file?

 When are these made changes made?

Source Code Management


Version Control System

 Each change to project can be considered a new version of the


project.

 Version Control System simplifies tracking changes to the project


and allow us switch back to any previous version.

There are several tools that help us manage versions of the source code of
software.

 Git

 Subversion

 Mercurial

Git

Git is a free, open-source and most widely used distributed version control
system.

 A software used for tracking changes in any set of files.

Repository

A Git Repository (Repo) is like a database which maintains different


versions of the project files.

Snapshots

 Git allows us to take a snapshot of our project files to create


versions of the project.

 These versions or snapshots are referred to as commits in Git


Terminology

Tracking Files

 By default, Git doesn’t track changes to a file and doesn’t maintain


versions automatically.

 We have to explicitly specify git to track file changes and save


versions.

Selecting Specific Changes

 Most of the times we want to have a selective set of changes as part


of the snapshot.

 Git creates a snapshot of all the changes that are part of staging
area.

Git’s View of Repository


Untracked Files : The set of files whose changes are not tracked by Git.

Tracked Files: The set of files which are watched by Git for any changes.

 Modified Files: These are the files which are modified after the latest
snapshot.

 Staged Files: The set of files which are about to be committed to


create a new snapshot.

 Committed Files: These are the unmodified files which are same
since the latest commit.

Distributed Version Control System

Git is a distributed version control system.

 Everyone has a copy of the entire repository with the entire version
history.

Git Repository

There are several cloud-based repository hosting services which let you
maintain a copy of repository

 GitHub

 Bitbucket

Create Account

Create Github account by visiting https://github.com

Creating a Repository

 Create a new Github repository using + button at top right corner of


website.
 After clicking on New repository button you can see screen similar to
below.

 After creating github repository you can be able to see screen


similar to below.
Sharing Repository

We can share the repository with other users on GitHub to collaborate.

 You can invite collaborators by visiting settings > Manage access


and clicking on Invite a collaborator.
Git Client

Installing git in your system to manage & work with Git Repositories.

In Linux :

sudo apt install git

In MAC :

sudo brew install git

Setting Author Info

Configure who gets credit for the changes made from your device by
setting the author details from your terminal.

git config --global user.name "Your Name"

git config --global user.email "youremailaddress@_Example_ .com"

Command Line Coloring For Git

To set automatic command line coloring for Git for easy reviewing.

git config --global color.ui auto

Viewing Git Client Configuration


You can check your current git client’s configuration with

git config -l

Sample output :

user.name=User

[email protected]

color.ui=auto

Cloning Repository

git clone

creates a copy of remote repository on your computer.

 Cloning a repository downloads all versions of the files that ever


existed to your computer.

 The

.git/

folder present in the repository contains all these versions and information
required for version control.

Example :

git clone https://github.com/icecream-dev/tutorial.git

Displaying the Remote

Lists the details of the configured remote repo.

git remote -v

Sample output :

origin https://github.com/icecream-dev/tutorial.git (fetch)

origin https://github.com/icecream-dev/tutorial.git (push)

Initializing a Git Repository

Apart from cloning a repo, you can also initialize a git repo in an existing
folder.

 Useful when you want to convert an existing, unversioned project to


a Git repository or initialize a new, empty repository.

 git init
initializes an empty git repository in the working directory.

Syntax :

git init

Adding Remote Repository

git remote add

can be used to configure a remote repository to the local repository.

Syntax :

git remote add origin URL

Example :

git remote add origin https://github.com/icecream-dev/tutoiral-2.git

Warning

From August 12, 2021, Github has disabled authentication of

git clone, git push and git pull commands with password. You need to
create a personal access token and use it for gitcommands instead of
password. The steps to create your personal access token are mentioned
in this link: Creating a Personal Access Token

Submit Feedback

Cheat Sheet

Staging Area & Commits

Creating a Commit

Working Directory

We shall refer the project folder as Working Directory.

Let’s add two files

alice.txt

and

bob.txt

to our working directory.

touch alice.txt

touch bob.txt
Git’s View of Repository

Inspecting a Repository

Git tracks the changes in the working directory.

 git status

shows the changes in the working directory

Making Changes

Added some content to

alice.txt

and

bob.txt

files.

alice.txt:
Hi

What about your learning

Is it going good?

bob.txt:

Hi

What's your name?

Steps in Creating a Commit

1. Add changes to the staging area.

2. Creating a commit with changes in staging area.

Step 1: Adding Changes To Staging Area

git add

adds the changes to the staging area.

Syntax :

git add file_path

Example :

git add alice.txt

Step 2: Committing Changes

commit

is a snapshot of the project's currently staged changes.

Syntax :

git commit -m "message"

Here

message

provide useful information about what has changed and why.

Example :

git commit -m "adds alice file"

Listing all commits

git log

lists all commits.


1

git log

Sample output :

Here HEAD refers to the current commit.

Commit Id

Commit IDs are unique strings(hashes) that are created whenever a new
commit is recorded.

8f00aaa0248bcdc38a8d8ba6267167a0478f5a63

is commit id in above Example .

Unstaged Changes

git diff

shows the unstaged changes.

git diff

Sample output :

diff --git a/alice.txt b/alice.txt

index e69de29..35dc461 100644

--- a/alice.txt

+++ b/alice.txt

@@ -0,0 +1,2 @@

+Hi

+What about your learning

+It’s going good

Uncommitted Changes
git diff --staged

shows the staged and uncommitted changes.

Working with Remote Repository

Pushing Commits

git push

command is used to publish new commits from local to a remote


repository.

Syntax :

git push -u origin master

Warning

From August 12, 2021, Github has disabled authentication of

git clone, git push and git pullcommands with password. You need to
create a personal access token and use it for gitcommands instead of
password. The steps to create your personal access token are mentioned
in this link: Creating a Personal Access Token

You can also edit file and commit changes through github Website

Editing File

 Click on the file you want to edit.

 Click on pencil icon to open editor :


Commit Changes

To commit changes click on Commit changes .

Get Commit Link

To share specific link of a commit, follow below steps:

 Click on commits to view all commits.


 Click on commit id of commit you want to share.

 Copy the url and share.

Pull Commits

git pull
is used to pull latest commits from a remote repository to your local
repository.

git pull origin master

Warning

From August 12, 2021, Github has disabled authentication of

git clone

git push

and

git pull

commands with password. You need to create a personal access token


and use it for

git

commands instead of password. The steps to create your personal access


token are mentioned in this link: Creating a Personal Access Token

Submit Feedback

Marked as complete

Notes

Top 50 Git Interview Questions and Answers

Last Updated : 18 Oct, 2024

Git is a distributed version control system (DVCS) designed to track


changes in source code during software development. In 2005, Linus
Torvalds, who is also the creator of the Linux kernel, developed it. Today,
more than 40 million people use Git universally. If you are a developer,
DevOps engineer, or any professional in the tech industry, knowing Git is
vital.

In this Git interview questions article, we will provide Top GitHub interview
questions and answers designed for both freshers and experienced
developers. To help you get ready for interviews, we have gathered
the top 50 Git interview questions for freshers, intermediate, and
experienced candidates. Going through these questions will boost your
chances of getting a job at top MNCs.

Table of Content

 Basic Git Interview Questions for Freshers

 Intermediate Git Interview Questions and Answers

 Advanced Git Interview Questions for Experienced

Basic Git Interview Questions for Freshers

1. What is Git?

Git is a distributed version control system (DVCS) that is used to track


changes in source code during software development. It permits multiple
developers to work on a project together without interrupting each other's
changes. Git is especially popular for its speed, and ability to manage both
small and large projects capably.

2. What is a repository in Git?

A Git repository (or repo) is like a file structure that stores all the files for a
project. It continues track changes made to these files over time, helping
teams work together evenly. Git can control both local repositories (on
your own machine) and remote repositories (usually hosted on platforms
like GitHub, GitLab, or Bitbucket), allowing teamwork and backup.

3. What is the difference between Git and GitHub?

Git GitHub

Git is a version control system GitHub is a platform where Git


used to track changes in files repositories can be stored and
over time shared

It runs locally on your


It is a cloud-based service
computer
Git GitHub

Git can be used offline, as it GitHub requires an internet


operates locally on your connection because it is hosted on
machine. the web

4. What is origin in Git?

In Git, "origin" states to the default name offered to the remote repository
from which local repository was cloned. It is used as a reference to control
fetches, pulls, and pushes.

5. What is the purpose of the .gitignore file?

The '.gitignore' file tells Git which files and folders to ignore when tracking
changes. It is used to avoid attaching unneeded files (like logs, temporary
files, or compiled code) to your repository. This saves repository clean and
targeted on important files only.

6. What is a version control system (VCS)?

A version control system (VCS) records the work of developers


coordinating on projects. It keeps the history of code changes, permitting
developers to add new code, fix bugs, and run tests securely. If required,
they can restore a past working version, verifying project security.

7. What is the git push command?

The 'git push' command is used to share local repository changes to a


remote repository. It changes the remote repository with the recent
commits from the fixed local branch.

8. What is the git pull command?

The 'git pull' command updates the current local branch with changes
from a remote repository and combining it with a local repository.

9. What does git clone do?

The 'git clone' forms a copy of a remote repository upon your local
machine. It downloads all files, branches, and history, enabling you to
start working on the project or contribute to it. With git clone -b , you can
download and work on an individual branch of a repository.

10. What are the advantages of using GIT?

Using Git provides multiple advantages:


 It assists teamwork by supporting multiple developers to work on
the same project together.

 Each developer has a local copy of the repository, improving


performance and enabling offline work.

 Free and widely supported.

 Git supports work on various types of projects.

 Each repository has only one Git directory.

11. What is the difference between git init and git clone?

'git init' develops a new, empty Git repository in the present directory,
while 'git clone' copies an existing remote repository, containing all files
and history, to a local directory.

12. What is git add?

The 'git add' command marks changes in your project for the next
commit. It tells Git which files to involve in the later update, making them
ready to be saved in the repository. This is the early step in recording
changes in the Git repository.

13. What is git status?

The 'git status' command shows the recent status of your Git repository. It
tells you which files have changed, which ones are ready to be committed,
and which ones are new and unobserved. This benefits you monitor your
work's growth and see what changes want to be set up or committed.

14. What is a commit in Git?

A commit in Git denotes a snapshot of changes made to files in a


repository. It grabs all the changes you have made to files—like additions,
or deletions of files at a particular moment. Each commit has a unique
message explaining what was done. This helps you track your project's
history, undo changes if requisite, and work with others on the same
project.

15. What is the purpose of the git clean command?

The 'git clean' command is used to erase ignored files from the working
directory of Git repository. Its motive is to clean up the workspace by
deleting files that are not being saved by Git, checking a clean state with
only observed files present.

16. What is a ‘conflict’ in git?


Git usually manages merges automatically, but conflicts occur when two
branches edit the same line or when one branch deletes a file that
another edits.

17. What is the meaning of “Index” in GIT?

In Git, the "Index" (also called as the "Staging Area") is a place where
alterations are temporarily store before committing them to the repository.
It permits you to select and prepare specific alterations from your working
directory before properly saving them as part of the project's history.

18. How do you change the last commit in git?

To change the preceding commit in Git, use 'git commit --amend' after
making changes, stage them with 'git add' , and save with the editor.

19. What is `git checkout`?

'git checkout' helps you switch between branches or return files to a


previous state in Git. Now, it is suggested to use 'git switch' for changing
branches and 'git restore' to return files. These commands are more intent
on their particular tasks for better clearness and capability.

20. How do you switch branches in Git?

To switch branches in Git, use 'git checkout ' to move to a present branch.
On the other hand, use git switch in newer Git versions for the same
objective. This permits you to work on different versions or features of
your project stored in separate branches.

21. Name some popular Git hosting services?

 GitHub

 GitLab

 SourceForge.net

 Bitbucket

 Visual Studio Online

Intermediate Git Interview Questions and Answers

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

'git fetch' fetches updates from a remote repository but does not combine
them into your local repository. It fetches all the new data from the remote
repository that you don’t have yet, but it stores it in a separate area,
permitting you to review the changes before merging them into your
working directory.
'git pull' fetches the updates from the remote repository and instantly
strives to merge them into your current branch. It is basically a union of
'git fetch' followed by 'git merge' .

23. Explain Git rebase and when do you use it?

Git rebase is a process to combine alterations from one branch into


another. It forms a linear history, avoiding merge commits. Use it to clean
up commit history, keep a project history sequential, and make feature
branches up-to-date before uniting.

24. How will you create a git repository?

 Download Git on your system if you have not already.

 Create a project folder in the location where you want your


repository.

 Open Terminal or Command Prompt and guide to your project folder.

 Run 'git init' in the project folder. This will create a '.git' folder,
showing your repository is set.

25. What differentiates between the commands git remote and git
clone?

'git clone' : Downloads a full copy of a remote repository to your local


computer, involving all files and history.

'git remote' : Controls connections to remote repositories. It sets up links


to remote repositories but doesn't download any files.

26. What are the benefits of using a pull request in a project?

Teams can together work on distinct parts of the system and later
combine their changes using pull requests. This way boosts team
capability.

27. What is a Git bundle?

A Git bundle is a collective file that wraps all data from Git repository,
such as commits, branches, and tags. It acts as a handy approach for
relocating a repository offline or sharing upgrades when network
connection is not available. To form a git bundle, perform the following
command:

git bundle create <bundle_file> <refs>

28. What are the advantages of Git over SVN?

 Git permits developers to work offline and autonomously, However


SVN needs a steady network connection to commit changes.
 Git is broadly rapid for most operations, containing branching,
merging, and committing, due to its distributed nature and efficient
data handling.

 Git supports various development workflows, such as feature


branching, pull requests, and decentralized collaboration, which is
adaptable to different team sizes and project needs.

29. What is git stash?

Git stash is Git command used to temporarily store changes in your


working directory that are not yet ready to be committed. It permits
developers to conserve modifications without committing them to the
repository.

30. How do you revert a commit that has already been pushed
and made public?

To revert a commit that has been pushed and made public, follow these
steps:

 Checkout the Branch: Switch to the branch where you want to revert
the commit.

git checkout <branch-name>

 Find the Commit to Revert: Use 'git log' to find the commit hash of
the commit you want to revert.

git log

 Revert the Commit: Use 'git revert' followed by the commit hash of
the commit you want to revert.

git revert <commit-hash>

 Review Changes: Git will open your default text editor to confirm the
revert message. Save and close the editor to proceed.

 Push the Revert: Finally, push the reverted commit to the remote
repository.

git push origin <branch-name>

31. Explain the difference between reverting and resetting?

Resetting: Resetting: This command is used to change the present state


of the repository to a precise point in its history. When you refresh, Git
moves the 'HEAD' (present branch) to the particular commit, likely
changing the files in your working directory and staging area. It is like
reversing to a definite point in time, and it can be used to discard
changes.

Reverting: Reverting, on the other a hand, makes new commit that


undoes the changes made by specific commit. In place of removing or
changing history like resetting does, reverting adds new commit that
effectively reverses the changes introduced by the commit you specify.

32. What is the difference between git reflog and log?

Git Log: It shows a history of commits (changes) made in your Git


repository. It lists out commits in linear order, showing who made each
change, when they made it, and the commit message.

Git Reflog: It stands for "reference log". It records changes to the HEAD
(current branch pointer) and permits you to see a timeline of recent
movements within the repository, like commits, checkouts, merges, etc. It
is effective for recovering lost commits or branches that are no longer
visible in the regular log.

33. What is the HEAD in Git?

In Git, HEAD is a source to the current branch or commit you are working
on. HEAD normally shows the recent commit of the current branch and
moves when you switch branches or check out exact commits.

34. What is the purpose of `git tag -a`?

The intent of 'git tag -a' is to form an annotated tag in Git. Annotated tags
are tags that contain additional metadata such as the tagger's name,
email, date, and a message. They are valuable for labeling important
points in history, like releases, and give another context compared to
lightweight tags made with 'git tag' .

35. What is the difference between `HEAD`, `working tree` and


`index` in Git?

HEAD: Points to the currently checked-out commit or branch.

Working Tree: Includes the actual files you are currently working on or
modifying.

Index (Staging Area): Acts as a middle ground where changes are


prepared before committing. It keeps snapshots of change to be included
in the next commit.

36. How to resolve a conflict in Git?

Discover Conflicting Files: Find the files where conflicts have take place
because of changes from unique branches.
Correct Files to Repair Conflicts: Alter the files to sync conflicting
changes and block future conflicts.

Stage solved Files: Use 'git add' to add the resolved files to the staging
area. Commit the Changes: Complete the process by committing the
changed files applying 'git commit' .

37. Explain the difference between `git merge` and `git rebase`
and when you would use each?

'git merge' merges changes from one branch into another, keeping
distinguish branch histories. It forms merge commits that directly show
where branches came together. 'git rebase' reforms history by using
commits from one branch onto another, causing in a linear sequence of
commits. Prefer 'merge' to keep distinct branch timelines and use 'rebase'
for enhancing commit history before merging branches.

38. What language is used in GIT?

Git is mainly developed using the C programming language. The core


features and commands of Git, containing its data structures and
algorithms, are applied in C. This choice of language confirms productivity,
speed, and portability across distinct operating systems and platforms.

39. How do you add a file to the staging area?

Use `git add <file_name>` to add a file to the staging area, forming it
ready for a commit.

40. What is `git diff`?

'git diff' is a command in Git that presents the differences between varied
states of files in a repository. It equates changes between the working
directory, the staging area (index), and the last commit. It assists track
changes, additions, and deletions before committing changes to the
repository.

Advanced Git Interview Questions for Experienced

41. What is the Git object model?

The Git object model comprises four major types: blobs (which store file
data), trees (which store directory structures), commits (which store
repository snapshots), and tags (which store references to commits).
These objects are the pillar of Git's version control system, permitting for
capable tracking and management of changes.

42. Explain `git rebase` and when you would use each?
'git rebase' moves commits from one branch to another, making a
straight, linear history. Use rebase to enhance and clean up the commit
history before merging.

43. What is a git hook and how might you use it?

A Git hook is a pattern script that instantly runs at exact points in the Git
workflow, such as before or after commits, merges, or pushes. You can use
hooks to apply coding rules, run tests, check for security faults, or simplify
tasks. For an example, a pre-commit hook can run and tests to verify code
quality before changes are committed.

44. How does Git store data?

Git stores data by saving snapshots of your project at diverse points in


time. Each snapshot is a commit, which covers information about the
project’s files (blobs) and directories (trees). These snapshots are
recognized by unique hashes, creating it easy to track changes and
retrieve history.

45. Explain what is meant by the "detached HEAD" state in Git?

When 'HEAD' points directly to a commit instead of a branch, Git is in a


detached 'HEAD' state. Changes made in this state won’t be referenced by
any branch and might be lost if not saved.

46. Explain the difference between git reset, git revert, and git
checkout?

 git reset: Moves HEAD to different commit, potentially changing


history.

 git revert: Undoes exact commit by making new commit with


inverse changes.

 git checkout: Switches branches or checks out files from commit,


putting you in "detached HEAD" state for direct commits.

47. How do you handle large files with Git?

To handle large files in Git, use Git LFS (Large File Storage). It tracks large
files severally from your repository, storing them on a remote server. This
prevents bloating your repository size and secures improved performance
while operations like cloning and fetching.

48. What is the function of the git cherry-pick command?

The git cherry-pick command uses exact commits from one branch to
another, allowing selective merging of changes without merging entire
branches.
49. What is ‘bare repository’ in Git?

A bare repository in Git is one missing a working directory. It only contains


version control data, making it ideal for sharing and collaboration without
changing files directly.

50. What is branching in Git?

Branching in Git permits forming separate lines of development. It allows


users to work on features or fixes separately from the main codebase,
helping parallel development and simpler integration of changes.

You might also like