0% found this document useful (0 votes)
4 views64 pages

Git and Github

Git is a widely used version control system that tracks changes in files, facilitates collaboration among developers, and supports non-linear development through branching. GitHub is a web-based platform that hosts Git repositories, offering additional features for project management and collaboration. The document outlines Git's workflow, commands, and the differences between Git and GitHub, as well as file status lifecycle and basic Git commands.

Uploaded by

thehsr484
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)
4 views64 pages

Git and Github

Git is a widely used version control system that tracks changes in files, facilitates collaboration among developers, and supports non-linear development through branching. GitHub is a web-based platform that hosts Git repositories, offering additional features for project management and collaboration. The document outlines Git's workflow, commands, and the differences between Git and GitHub, as well as file status lifecycle and basic Git commands.

Uploaded by

thehsr484
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/ 64

Git and GitHub

What is Git?
Git is the most commonly used version control system. Git
tracks the changes you make to files, so you have a record
of what has been done, and you can revert to specific
versions should you ever need to. Git also makes
collaboration easier, allowing changes by multiple people
to all be merged into one source.

 Git is used to tracking changes in the source code

 The distributed version control tool is used for source code


management

 It allows multiple developers to work together

 It supports non-linear development through its thousands of


parallel branches

Features of Git

 Tracks history

 Free and open source

 Supports non-linear development

 Creates backups

 Scalable

 Supports collaboration

 Branching is easier

 Easily recover files

 Who introduced an issue and when?


Git and GitHub
 Roll back to previously working state

 Distributed development

So regardless of whether you write code that only you will


see, or work as part of a team, Git will be useful for you.

Git Workflow
Git and GitHub

The Git workflow is divided into three states:

 Working directory - Modify files in your working directory

 Staging area (Index) - Stage the files and add snapshots


of them to your staging area

 Git directory (Repository) - Perform a commit that stores


the snapshots permanently to your Git directory.
Checkout any existing version, make changes, stage
them and commit (This is three stage architecture of
git).
Git and GitHub

Note: We should write the changes of our files or projects in commit when
we use the commit command in git.

Ex: Git commit -m “Write changes of file for your better appearance”

What is a Version Control System?


The Git version control system, as the name suggests,
is a system that records all the modifications made to a
file or set of data so that a specific version may be
called up later if needed. The system makes sure that
all the team members are working on the file’s latest
version, and everyone can work simultaneously on the
same project.

What is GitHub
Git and GitHub
GitHub is an increasingly popular programming
resource used for code sharing. It's a social networking
site for programmers that many companies and
organizations use to facilitate project management and
collaboration. According to statistics collected in
October 2020, it is the most prominent source code
host, with over 60 million new repositories created in
2020 and boasting over 56 million total developers.

Git vs GitHub:
The main Git vs GitHub difference is in their
functionality. While they both provide source code
management (SCM) and make merging and sharing
code easier, this is pretty much where their similarities
end. Think of Git as a single computer and GitHub as a
network of multiple interconnected computers, all with
the same end goal but a wildly different role for how to
get there.

At its core, Git is a free, open-source software


distributed version control system (DVCS) designed to
manage all source code history. It can keep a history of
commits, can reverse changes, and lets developers
share code. Each developer must have Git installed on
his or her local device to collaborate. It is commonly
referred to as one of the best DevOps tools to
understand and use in the developer space, and it’s
among the most widely used tools today. Companies
like Amazon, Facebook, and Microsoft use it, to name a
few.
Git and GitHub
GitHub, on the other hand, is a web-based hosting
service for Git repositories. It offers all of Git’s DVCS
SCM and has some additional features. This includes
collaboration functionality like project management,
support ticket management, and bug tracking. With
GitHub, developers can share their repositories, access
other developers’ repositories, and store remote copies
of repositories to serve as backups.

Branch in Git
Branch in Git is used to keep your changes until they
are ready. You can do your work on a branch while the
main branch (master) remains stable. After you are
done with your work, you can merge it with the main
office.
Git and GitHub

The above diagram shows there is a master branch.


There are two separate branches called “small feature”
and “large feature.” Once you are finished working with
the two separate branches, you can merge them and
create a master branch.

File status life cycle in git


When you start to track files on an empty repository
every file stays in the untracked stage. Which means
we have not staged these files. So after adding the files
by typing “git add --a”, every file moves into the
unmodified section. Now if we change a few files they
will be moved to modified and staged. Now what
happened here is, we have added every file to the
tracker and now as we modify files will be moved to the
modified phase. Now if we run the add command then
the files which were in the modified stage will be
staged.
Git and GitHub
 Let’s open a new folder and initialize as a git repo by
opening Git bash and typing “git init”

 Now lets add the files by using “git add --a”.

 Now every file has been staged.

 Now if we change 1 file and do “git status” then you will


see that the file we changed is present both on staging
area and untracked area. Because you have staged the
file and those are meant to go to the commit until the user
stages other changes. So only those will go to the next
commit which are staged. The untracked files will be
ignored unless the user adds them to stage.

File has four states in Status lifecycle. that are:

Untracked
Unmodified
Modified
Staged
1. Untracked state : Files are present in the local directory,
but not added in the github repository index.
2. Unmodified state : Files are already present in directory
or added using $git add command. If some changes did,
then it not get tracked. Also after commiting the
changes file status become unmodified.
3. Modified state : When previously tracked file is edited,
but not commit the changes.
4. Staged state : When files committed and ready to push
in git repository, then they have staged status.
Git and GitHub

File has two states tracked and untracked. Previous


snapshot are maintained in tacked file.
Git and GitHub

Basic git commands:


s.no. Commands Description

1 Git Show git information


and some basic
commands.
2 Pwd Show your current
directory/location.

3 Ls Show all content/files


of current directory.

4 Cd folder_name Change directory.

5 Cd /drive_character Go direct on c drive


Ex.- cd /c, cd /a or any other drive.

6 Git config –global user.name Set user name.


“User_name”

7 Git config –global user.email Set user email ID.


“Email_ID”

8 Git config –list Show entered user


name and email ID
and other many
information.
9 Git config –global Set a linux editor.
core.editor editor_name
Ex.- git config –global
core.editor emacs/vim/..etc.
10 Git config user.name Show your entered
user name.
Git and GitHub
11 Git config user.email Show your entered
email address.

12 Clear Clear the git bash


screen.

13 Cat filename.extension View file data.

12 Git status For checking the


status of git
repository and also
check that it is a git
repository
(directories) or not.
13 Git status -s Show status in sort.

13 Git init For making a git


repository.

14 Git add --a or git add -A Put all files in


or git add . staging area.

15 Git commit -m “Write For making commit


message” (snapshot).

16 Git log Show all commits.

17 Git log -p -number Show last number of


Ex: git log -p -5 commits.
Ex: show last 5
commits.
17 Git add file_name.extension Put a file in staging
area for commit
after changes .
18 Rm -rf .git For closing the
tracking of any
folder and delete
Git and GitHub
your git repository.

Note:- this may be


risky sometimes for
your project if git
repository is already
exist because it will
delete your git
repository after that
neither you track
your project nor roll
back in your project ,
that’s why don’t use
this command if your
project is useful or
important.
19 Git clone Type_URL_here Make a clone by
folder_name using URL of any
project/app/website/.
.etc. which is
available on internet
and put this project
in a folder.
Folder_name is
optional but if we
don’t make a folder
then git will make a
folder by default
according the
cloning project.
20 Touch file_name.extension For creating a new
Ex:- touch error.log file in current
directory.
Touch hsr.txt
21 Touch .gitignore Make a .gitignore file
for ignore one or
more files which are
Git and GitHub
not important such
Note:- this is for only as .log, .txt etc. we
untracking files. can make .gitignore
file and push
If we put any file unnecessary files
in .gitignore file which is in .gitignore and
currently untracking by git after that git will not
and we don’t want to track track these files .
those files then we can put
those files in .gitignore file
otherwise if any file is For push/insert files
already tracking by git and in .gitignore:
if we put that file Open .gitignore file
in .gitignore and after that and type file name
if we change that file than with extension which
git will track the changes. files you want to
ignore.
Ex- Hsr.txt, error.log
etc.
You can also ignore
a folder or directory.
Open .gitignore >
type folder_name/
Note: / indicate that
it is a folder.
Ex- my new data/
Now git will not track
these files or folders.

Note : git ignore


empty folders by
default.

Note : if you make a


folder and in this
folder you make a
Git and GitHub
another folder of
same name which
you have ignored
than git will not track
these folder even
you create new files
in this folder.
But if you want to
track this another
folder then:
Open .gitignore >
type /folder name
Now git will ignore
only this folder not
another folder of
same names.

Note: if we are tracking a file and if we put this file


in .gitignore file and after that if we change this file than git
will track this changes because earlier git was tracking this
file.
22 Git rm –cached Stop tracking a file
filename.extension permanently until we
don’t track that file
again.
23 Open .gitignore file and Now git will ignore
type: all .log and .txt files.
*.log
*.txt
24 Git diff Compare staging
area with working
directory.
(Compare two file if
one file is in staging
area and also is
modified).
Git and GitHub
25 Git diff –staged Compare your last
commit with current
staging area.
26 Git commit -a -m “Write Commit tracked files
message/changes ” and skip staging
area.
Note: this is for only
tracked files,
untracked files will
not be commit.
27 Git log Show all commit.
Press q for quit/exit
from commit section.
28 Git log -p Show all commit with
removed data and
new added data or
we can say it will
show all commit will
all changes.
Press q for quit/exit
from commit section.
29 Git log --stat Show all commit
shortly.

30 git log --pretty=oneline Show one commit in


one line.

31 git log --pretty=short Show all commit with


few important details
shortly.
32 Git log --pretty=full Show all commit with
more details.

33 Git log -- Show all commit of


since=number.days/.weeks/. last number of
months/.years days/weeks/months/
years.
Git and GitHub
Ex: git log --since=2.days
Ex: show all commit
of last 2 days.
34 Git rm filename.extension Remove or delete a
file and also stage.

35 Git mv Rename a file and


old_file_name.extension move in staging
new_file_name.extension area.
36 Git commit --amend For amend a commit
and modify a commit
on wim editor.

For run the wim


editor:
1. Press I or
insert key
for writing.
2. Press
escape >
press : >
type wq >
press
enter.

Now your commit


will be amend.
37 Git restore --staged For unstage a file if
filename.extension file is in staging
area.
38 Git checkout Discard all last
filename.extension changes of a file or
Or Roll back to
previously working
Git restore state if file is not in
filename.extension staging area, only
Git and GitHub
file is modified.
39 Git checkout -f Discard all last
changes in multiple
files at once.
40 Git --version Show git version.

41 Git remote Show remote.

42 Git remote -v Show address from


where we are doing
pull and push.
43 Git push origin -u master Push your master
branch on github.

44 Git push origin Push your other


branch_name branch on github.

45 Git push origin Push any branch


branch_name:New_branch_n with other new name
ame on github.
46 Git branch -d branch_name Delete a branch from
your system only.

47 Git push -d origin Delete a branch from


branch_name remote or github.

48 Git push -u origin Push a branch on


branch_name github or other
remote server.
48 Git pull origin branch_name Show all changes of
branch in git which
you did on github or
pull all changes.

Git Revert
Git and GitHub
In Git, the term revert is used to revert some changes. The git
revert command is used to apply revert operation. It is an
undo type command. However, it is not a traditional undo
alternative. It does not delete any data in this process;
instead, it will create a new change with the opposite effect
and thereby undo the specified commit. Generally, git revert
is a commit.

It can be useful for tracking bugs in the project. If you want to


remove something from history then git revert is a wrong
choice.

Moreover, we can say that git revert records some new


changes that are just opposite to previously made commits.
The revert command will create a commit that reverts the
changes of the commit being targeted. You can use it to
revert the last commit like this:
git revert <commit to revert>
You can find the name of the commit you want to revert
using git log. The first commit that's described there is the
last commit created. Then you can copy from there the
alphanumerical name and use that in the revert command.
Git and GitHub
If you roll back second time, than:
Type git revert -n and paste commit id.

Hard reset
You can also use the reset command to undo your last commit.
But be careful – it will change the commit history, so you
should use it rarely. It will move the HEAD, the working
branch, to the indicated commit, and discard anything after:
git reset --soft HEAD~1
The --soft option means that you will not loose the
uncommitted changes you may have.

If you want to go at any status and you realize that what ever
I changed after that state those are not useful and you want
to roll back at that working stage and delete all commit after
that working stage than you can use --hard option.
1. Run git log command : for watching all commit.
2. Copy the commit id to which stage you want to go
back.
3. Type git reset --hard and paste the commit id

Now hard reset has been completed.

Working with Remote


Repositories
Git and GitHub
Let’s start by going to Github’s official website and creating
an account. After you have created your account you need to
go to the home page and click on the create a new repository
option. Now give your repository a name and description. Now
click on create repository. Now it will show you a page for
quick setup. Now let’s make our local repository a remote
repository.

Note: before pushing your code on github make sure that you
are in that branch which you want to push on github. And also
check that your working tree is clean or nothing to commit
otherwise first you will have to commit them.

Steps:
 Go to your local directory and open git bash there.
 Now we have 2 options, 1: If we have not created a git
repository in our system then follow the first method, 2:
We have a git repo in our local system we just want to
push it to the remote system then follow the method 2.
 We are following Method 2 Here.
 So let’s copy the code on git’s website which looks like
this “git remote add
origin [email protected]:yourusername/repositoryname.git
” and paste it to the git bash and press enter.
 Now we will paste the second command which pushes
the files onto the remote server which is “git push -u
origin master”.
 It will give you an error that access is denied if you are
doing it first time. Now let’s tackle this.
 To fix it, go to your account settings on github, then SSH
and GPG keys. Then click on the new SSH key, add a
title. Now for the key, open git bash and follow the
simple steps.
 On git bash type the following edit your email and press
enter: “ssh-keygen -t rsa -b 4096 -C
Git and GitHub
"[email protected]" ”
 Now just simply press enter 3 times.
 Now run this command “eval $(ssh-agent -s)”.
 Now run this “ssh-add ~/.ssh/id_rsa”.
 Now on git bash type this to reveal your key “tail
~/.ssh/id_rsa.pub”.
 Now it will show you the ssh key. Just simply copy it.
 And now let’s head back to the github SSH key page and
paste the key to the key field, press add ssh key. And
done!
 Now if you run “git push -u origin master” it will run and
push your files to github.
Note: if it will show an fatal error (remote: Repository not
found), than you need to switch in SSH.
1. Click on SSH and copy URL.
2. Open git and type: $ “git remote set-url origin
Paste_URL” and press enter.
 Now you can make changes on your local git repo and
push the changes to the remote repo swiftly.

Now we will push our other branches to github. First let’s


switch the branch by typing “git checkout branchname”. And
if we now type “git push origin branchname” and press enter,
it will push that branch to github and we can check that on
github.
We can also merge our branches to the main branch and push
the changes. We need to switch to the main branch first by
typing “git checkout master” Now we will merge the branch
by typing “git merge branchname” and merge it. Now we will
delete the unnecessary branch by typing “git branch -d
branchname”. Now if we do “git status” it will show us only
the main branch. And now we will push the changes by typing
“git push -u origin master”. Now also remove the branch from
remote repository too by typing “git push -d origin
branchname”. And now if you check on github you will see
Git and GitHub
that the branch has been deleted.

Branches in git

Basic commands for branches:

Note: when we switch from one branch to another branch


than make sure that previous branch is commit by you for a
safe and clean zone.

Git checkout -b New_branch_name - creating


and switching in a new branch.
Git checkout branch_name - switch
from one branch to another branch.
Git branch - show all
branches.
Git branch -v - show last
commit message and it’s hash code of all branches.
Git merge branch_name - merge
branch.
Git branch --merged - show all
merged branches.
Git branch --no-merged - show
unmerged branches.
Git branch -d branch_name - delete a
branch if it is already merged otherwise it will give an error.
Git branch -D branch_name - delete a
branch even branch is not merged.

Note: when we create a new branch and what ever we


change(modify, delete, create file , etc.) in our project
Git and GitHub
with new branch than another branch is not affected.
Now if we switch to our old branch again, it remains
the same as it was before.

Basic Branching and Merging


Let’s go through a simple example of branching and merging
with a workflow that you might use in the real world. You’ll
follow these steps:
1. Do some work on a website.
2. Create a branch for a new user story you’re
working on.
3. Do some work in that branch.
At this stage, you’ll receive a call that another issue is critical
and you need a hotfix. You’ll do the following:
4. Switch to your production branch.
5. Create a branch to add the hotfix.
6. After it’s tested, merge the hotfix branch, and
push to production.
7. Switch back to your original user story and
continue working.
Git and GitHub

Basic Branching
First, let’s say you’re working on your project and have a
couple of commits already on the master branch.

You’ve decided that you’re going to work on issue #53 in


whatever issue-tracking system your company uses. To
create a new branch and switch to it at the same time, you
can run the git checkout command with the -b switch:
$ git checkout -b iss53

Switched to a new branch "iss53"


This is shorthand for:
$ git branch iss53
Git and GitHub
$ git checkout iss53

how to merge branches:

 Open Git Bash on your local repository.


 Let’s create a branch by typing “git checkout -b
branchname”.
 Now if you modify the files in the repo and do “git
status” it will show you “on Branch branchname”
which means you are changing files on the
branch you have created.
 Let’s stage these files by using “git add .” and
commit these changes by typing “git commit -m
“commit message” ”.
 Now if you do “git checkout master” then you will
see that the files on your repo will revert to the
master branch where we haven’t made any
changes.
 Now if we do “git merge branchname” it will
Git and GitHub
merge those branches.
 Now we just need to stage and commit those
changes by typing “git add .” & “git commit -m
“commit message” ”.
Git Merge Conflict
When two branches are trying to merge, and both are
edited at the same time and in the same file, Git won't
be able to identify which version is to take for
changes. Such a situation is called merge conflict. If
such a situation occurs, it stops just before the merge
commit so that you can resolve the conflicts
manually.
Git and GitHub
Let's understand it by an example.

Suppose my remote repository has cloned by two of


my team member user1 and user2. The user1 made
changes as below in my projects index file.

Update it in the local repository with the help of git


add command.

Now commit the changes and update it with the


remote repository. See the below output:
Git and GitHub
Now, my remote repository will look like this:

It will show the status of the file like edited by whom


and when.

Now, at the same time, user2 also update the index


file as follows.

User2 has added and committed the changes in the


local repository. But when he tries to push it to
remote server, it will throw errors. See the below
output:
Git and GitHub

In the above output, the server knows that the file is


already updated and not merged with other branches.
So, the push request was rejected by the remote
server. It will throw an error message like [rejected]
failed to push some refs to <remote URL>. It will suggest
you to pull the repository first before the push. See
the below command:
Git and GitHub

In the given output, git rebase command is used to


pull the repository from the remote URL. Here, it will
show the error message like merge conflict in <filename>.

How to Resolve Merge Conflicts in Git?

There are a few steps that could reduce the steps


needed to resolve merge conflicts in Git.

1. The easiest way to resolve a conflicted file is to


open it and make any necessary changes
2. After editing the file, we can use the git add
a command to stage the new merged content
3. The final step is to create a new commit with
Git and GitHub
the help of the git commit command
4. Git will create a new merge commit to finalize
the merge
Let us now look into the Git commands that may play
a significant role in resolving conflicts.

Resolving Conflicts by using VS Code:

There are many ways to resolve conflicts on Git


Merge. But we are going to use the easiest one. By
using VSCode. Just Install VS Code in your system and
open those files who have conflicts, and you will see 2
options: Current Change and Incoming change. Just
like this.

Just choose Accept Incoming change. Save the file and


commit the files by typing “git add .”, and “git commit
-m “message” ”. Now you have successfully merged 2
branches.

Git Commands to Resolve Conflicts

1. GIT LOG --MERGE

The git log --merge command helps to produce the list


Git and GitHub
of commits that are causing the conflict

2. GIT DIFF

The git diff command helps to identify the differences


between the states repositories or files

3. GIT CHECKOUT

The git checkout command is used to undo the


changes made to the file, or for changing branches

4. GIT RESET --MIXED

The git reset --mixed command is used to undo


changes to the working directory and staging area

5. GIT MERGE --ABORT

The git merge --abort command helps in exiting the


merge process and returning back to the state before
the merging began

6. GIT RESET

The git reset command is used at the time of merge


conflict to reset the conflicted files to their original
state
Git and GitHub

Git Branching Workflow in


Production

When people usually use git they create branches and


primarily they create 2 types of branches.

Long Running Branches:


A long-running branch is a branch under active development
that is not merged to the main branch for a long time. The
main branch might be, for example, master or develop.

Topic Branches:
Topic branch is a short lived branch which was created for a
single particular feature or related work. Topic branches can
Git and GitHub
be deleted after the particular feature is added to the project.

Example:

Let’s assume you were working on a project where you have


committed C1 on the master branch and then an issue has
arised and to solve that issue you have created a new branch
called issue and you have committed C2 and you came back
to master to complete the work and committed C3 on master
and went to the issue branch and committed C4, C5 and C6.
When you were on C4 you came across another new issue
and to fix that you have again created another new branch
called Issue1 V2 and committed C7, C8 and C11 where you
have solved that issue. After that you came to the Master
branch and committed to C9, C10 and you got an idea. To
implement the idea you created another branch named IDEA
and committed C12 and C13. Now you want to Merge IDEA on
to Master. Also you want to commit Issue1 V2 too. Now you
have merged C11 of Issue1 V2 branch and C13 of IDEA
branch and created a commit named C14 which is your
master branch.

Master

Idea C1
4 Issue solve
implement

C1
C1
1
3

C6
C1 C8
2

C1
C5
0 C7

C9

C4

C3
C2
Git and GitHub

Git alias
Git aliases are a powerful workflow tool that create shortcuts
to frequently used Git commands. Using Git aliases will make
you a faster and more efficient developer. Aliases can be used
to wrap a sequence of Git commands into new faux Git
command. Git aliases are created through the use of the git
config command which essentially modifies local or global Git
config files.

Types of Git Aliases

A Git alias can be either local or global. A local alias is defined


for a particular git repository whereas a global alias can be
used in any repository. If you create an alias inside a git
repository without the global flag, then the alias will be local
by default i.e. it can be used in the current repository only.
Alias created with global flags can be used in any git
Git and GitHub
repository.

How to create an alias in git?

An alias is created by using the following syntax:


git config –global alias.<custom_command_name>
<original_command Name>

For example:
$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
$ git config --global alias.st status

Aliases can also be used to create a new command


from a sequence of git commands.
For example,
git config --global alias.unstage 'reset HEAD --'
Here we have combined reset and HEAD command to create
a new git command.

Benefits of using Git Aliases


1. Git aliases can make you a faster and more efficient
developer as it can save you a lot of keystrokes in the
long run. For example, git commit is a frequently used
command, using git ci every time instead of git commit
is going to save a few keystrokes.
2. It makes the command look simpler and clearer.
Git and GitHub

 Placeholders that expand to information extracted


from the commit:
%H

commit hash
%h

abbreviated commit hash


%T

tree hash
%t

abbreviated tree hash


%P

parent hashes
%p

abbreviated parent hashes

%an

author name
%aN

author name
%ae

author email
Git and GitHub
%aE

author email
%al

author email local-part (the part before the @ sign)


%aL

author local-part
%ad

author date (format respects --date= option)


%aD

author date, RFC2822 style


%ar

author date, relative


%at

author date, UNIX timestamp


%ai

author date, ISO 8601-like format


%aI

author date, strict ISO 8601 format


%as

author date, short format (YYYY-MM-DD)


%ah

author date, human style


%cn

committer name
Git and GitHub
%cN

committer name
%ce

committer email
%cE

committer email
%cl

committer email local-part (the part before the @ sign)


%cL

committer local-part
%cd

committer date (format respects --date= option)


%cD

committer date, RFC2822 style


%cr

committer date, relative


%ct

committer date, UNIX timestamp


%ci

committer date, ISO 8601-like format


%cI

committer date, strict ISO 8601 format


%cs

committer date, short format (YYYY-MM-DD)


Git and GitHub
%ch

committer date
%d

ref names
%D

ref names without the " (", ")" wrapping.


Ex:- git log --pretty=format:"%h -- %aN - %T" - this will show all commit in following ways.

All git commands with group:


Tell Git who you are
Description Command
Configure the author git config --global user.name
name. "<username>"
Configure the author git config --global user.email
email address. <email address>

Getting & Creating Projects


Description Command
Initialize a local Git
git init
repository
git clone
Create a local copy of
ssh://[email protected]/<username>/<re
a remote repository
pository-name>.git

Basic Snapshotting
Description Command
Check status git status
git add <file-
Add a file to the staging area
name.txt>
Add all new and changed files git add -A or
Git and GitHub
Description Command
to the staging area git add .
git commit -m
Commit changes
"<commit message>"
git rm -r <file-
Remove a file (or folder)
name.txt>

Inspection & Comparison


Description Command
View changes git log
View changes git log --
(detailed) summary
git log --
oneline or
git log --
View changes in one
pretty=oneline
line (briefly)
or
git log --
pretty=short

Undo to previous file


Description Command
List of all commit with commit id and
git log --oneline
commit message)
git
Return to previous commit checkout<commit
id>
Revert commit (undo one particular git revert
commit) <commit id>
Reset to previous commit (remove git reset <commit
history of all commit after ) id>
git rm --cached
Stop a file being tracked
<file/folder>
git checkout
Restore a file to a previous commit
<file/to/restore>

Branching & Merging


Git and GitHub
Description Command
List branches (the asterisk
git branch
denotes the current branch)
List all branches (local and
git branch -a
remote)
Create a new branch git branch <branch name>
Create a new branch and git checkout -b <branch
switch to it name>
Clone a remote branch and git checkout -b <branch
switch to it name> origin/<branch name>
git branch -m <old branch
Rename a local branch
name> <new branch name>
Switch to a branch git checkout <branch name>
Switch to the branch last
git checkout -
checked out
Discard changes to a file git checkout -- <file-name.txt>
Delete a branch git branch -d <branch name>
git push origin --delete <branch
Delete a remote branch
name>
Preview changes before git diff <source branch>
merging <target branch>
Merge a branch into the active
git merge <branch name>
branch
Merge a branch into a target git merge <source branch>
branch <target branch>
Stash changes in a dirty
git stash
working directory
Remove all stashed entries git stash clear

Sharing & Updating Projects


Description Command
Push a branch to your
git push origin <branch name>
remote repository
Push changes to
remote repository
git push -u origin <branch name>
(and remember the
branch)
Git and GitHub
Description Command
Push changes to
remote repository git push
(remembered branch)
Delete a remote
git push origin --delete <branch name>
branch
Update local
repository to the git pull
newest commit
Pull changes from
git pull origin <branch name>
remote repository
git remote add origin
Add a remote
ssh://[email protected]/<username>/<re
repository
pository-name>.git
git remote set-url origin
Set a repository's
ssh://[email protected]/<username>/<re
origin branch to SSH
pository-name>.git
Git and GitHub

Basic Git Questions


1. WHAT IS GIT?

Git is a version control system for tracking changes in


computer files and is used to help coordinate work
among several people on a project while tracking
progress over time. In other words, it’s a tool that
facilitates source code management in software
development.

Git favors both programmers and non-technical users


by keeping track of their project files. It enables
multiple users to work together and handles large
projects efficiently.
Git and GitHub
2. WHAT DO YOU UNDERSTAND BY THE
TERM ‘VERSION CONTROL SYSTEM’?

A version control system (VCS) records all the changes


made to a file or set of data, so a specific version may
be called later if needed.

This helps ensure that all team members are working


on the latest version of the file

3. WHAT’S THE DIFFERENCE BETWEEN


GIT AND GITHUB?

Git GitHub

Git is a software GitHub is a service


Git and GitHub
Git can be installed locally on the GitHub is hosted on
system the web

Provides a desktop
Provides a desktop interface called
interface called
git GUI
GitHub Desktop.

It does not support user Provides built-in user


management features management

4. WHAT IS A GIT REPOSITORY?

Git repository refers to a place where all the Git files


are stored. These files can either be stored on the local
repository or on the remote repository.

5. HOW CAN YOU INITIALIZE A


REPOSITORY IN GIT?

If you want to initialize an empty repository to a


directory in Git, you need to enter the git init command.
After this command, a hidden .git folder will appear.
Git and GitHub

6. HOW IS GIT DIFFERENT FROM


SUBVERSION (SVN)?

GIT SVN

SVN is a centralized
Git is a distributed decentralized
version control
version control system
system.

Git stores content in the form of SVN stored data in


metadata. the form of files.

The master contains the latest In SVN, the trunk


stable release. directory has the
Git and GitHub
latest stable release

The contents of Git are hashed using SVN doesn’t support


the SHA-1 hash algorithm. hashed contents.

7. NAME A FEW GIT COMMANDS WITH


THEIR FUNCTION.

 Git config - Configure the username and email


address
 Git add - Add one or more files to the staging
area
 Git diff - View the changes made to the file
 Git init - Initialize an empty Git repository
 Git commit - Commit changes to head but not to
the remote repository

8. WHAT ARE THE ADVANTAGES OF


USING GIT?

 Faster release cycles


 Easy team collaboration
 Widespread acceptance
 Maintains the integrity of source code
 Pull requests
Git and GitHub

9. WHAT LANGUAGE IS USED IN GIT?

 Git is a fast and reliable version control system,


and the language that makes this possible is ‘C.’
 Using C language reduces the overhead of run
times, which are common in high-level
languages.

10. WHAT IS THE CORRECT SYNTAX TO


ADD A MESSAGE TO A COMMIT?

 git commit -m "x files created"

11. WHICH COMMAND IS USED TO


CREATE AN EMPTY GIT REPOSITORY?

git init - This command helps to create an empty


repository while working on a project.
Git and GitHub
12. WHAT DOES GIT PULL ORIGIN
MASTER DO?

The git pull origin master fetches all the changes from
the master branch onto the origin and integrates them
into the local branch.

git pull = git fetch + git merge origin/ master

After having gone through the beginner level Git


interview questions, let us now look at intermediate GIT
interview questions and answers.

Intermediate Git Interview


Questions
13. WHAT DOES THE GIT PUSH
COMMAND DO?

The Git push command is used to push the content in a


local repository to a remote repository. After a local
repository has been modified, a push is executed to
share the modifications with remote team members.
Git and GitHub

14. DIFFERENCE BETWEEN GIT FETCH


AND GIT PULL.

Git Fetch Git Pull

Git pull updates the


The Git fetch command only current HEAD branch
downloads new data from a remote with the latest
repository. changes from the
remote server.

It does not integrate any of these Downloads new data


new data into your working files. and integrate it with
the current working
Git and GitHub

files.

Tries to merge
remote changes with
Command - git fetch origin
your local ones.
git fetch --all
Command - git pull
origin master

15. GITHUB, GITLAB AND BITBUCKET ARE


EXAMPLES OF GIT REPOSITORY _______
FUNCTION?

hosting. All the three are services for hosting Git


repositories

16. WHAT DO YOU UNDERSTAND ABOUT


THE GIT MERGE CONFLICT?

A Git merge conflict is an event that occurs when Git is


unable to resolve the differences in code between the
two commits automatically.

Git is capable of automatically merging the changes


only if the commits are on different lines or branches.
Git and GitHub

17. HOW DO YOU RESOLVE CONFLICTS IN


GIT?

Here are the steps that will help you resolve conflicts in
Git:

 Identify the files responsible for the conflicts.


 Implement the desired changes to the files
 Add the files using the git add command.
 The last step is to commit the changes in the file
with the help of the git commit command.

18. WHAT IS THE FUNCTIONALITY OF GIT


LS-TREE?

The git ls-tree command is used to list the


contents of a tree object.
Git and GitHub

19. WHAT IS THE PROCESS TO REVERT A


COMMIT THAT HAS ALREADY BEEN
PUSHED AND MADE PUBLIC?

There are two processes through which you can revert


a commit:

1. Remove or fix the bad file in a new commit and push


it to the remote repository. Then commit it to the
remote repository using:

git commit –m “commit message”

2. Create a new commit to undo all the changes that


were made in the bad commit. Use the following
command:

git revert <commit id>

20. HOW IS A BARE REPOSITORY


DIFFERENT FROM THE STANDARD WAY
OF INITIALIZING A GIT REPOSITORY?

Standard way Bare way

You create a working directory with Does not contain any


Git and GitHub
working or checked
the git init command. out copy of source
files.

Bare repositories
store git revision
A .git subfolder is created with all history in the root
the git-related change history. folder of your
repository instead of
the .git subfolder.

21. WHAT DOES GIT CLONE DO?

Git clone allows you to create a local copy of the


remote GitHub repository. Once you clone a repo, you
can make edits locally in your system rather than
directly in the source files of the remote repo

22. WHAT IS GIT STASH?

Let’s say you're a developer and you want to switch


branches to work on something else. The issue is you
don’t want to make commits in uncompleted work, so
you just want to get back to this point later. The
solution here is the Git stash.

Git stash takes your modified tracked files and saves it


on a stack of unfinished changes that you can reapply
Git and GitHub
at any time. To go back to the work you can use the
stash pop.

23. WHAT DOES THE GIT RESET --MIXED


AND GIT MERGE --ABORT COMMANDS DO?

git reset --mixed is used to undo changes made in the


working directory and staging area.

git merge --abort helps stop the merge process and


return back to the state before the merging began.

24. WHAT DO YOU UNDERSTAND ABOUT


THE STAGING AREA IN GIT?

The Staging Area in Git is when it starts to track and


save the changes that occur in files. These saved
changes reflect in the .git directory. Staging is an
intermediate area that helps to format and review
commits before their completion.

25. WHAT IS GIT BISECT AND HOW DO


YOU USE IT?

The Git Bisect command performs a binary search to


detect the commit which introduced a bug or
regression in the project’s history.

Syntax: git bisect <subcommand> <options>


Git and GitHub
26. HOW DO YOU FIND A LIST OF FILES
THAT HAS BEEN CHANGED IN A
PARTICULAR COMMIT?

The command to get a list of files that has been


changed in a particular commit is:

git diff-tree –r {commit hash}

 -r flag allows the command to list individual files


 commit hash lists all the files that were changed
or added in the commit.

27. WHAT IS THE USE OF THE GIT CONFIG


COMMAND?

The git config command is used to set git configuration


values on a global or local level. It alters the
configuration options in your git installation. It is
generally used to set your Git email, editor, and any
aliases you want to use with the git command.

28. WHAT IS THE FUNCTIONALITY OF GIT


CLEAN COMMAND?

The git clean command removes the untracked files


from the working directory.

29. WHAT IS SUBGIT AND WHY IS IT


USED?
Git and GitHub
SubGit is a tool that is used to migrate SVN to Git. It
transforms the SVN repositories to Git and allows you to
work on both systems concurrently. It auto-syncs the
SVN with Git.

30. IF YOU RECOVER A DELETED BRANCH,


WHAT WORK IS RESTORED?

The files that were stashed and saved in the stashed


index can be recovered. The files that were untracked
will be lost. Hence, it's always a good idea to stage and
commit your work or stash them.

Now let’s raise the level of difficulty with advanced Git


interview questions and answers.

Advanced Git Interview


Questions
31. EXPLAIN THE DIFFERENT POINTS
WHEN A MERGE CAN ENTER A
CONFLICTED STAGE.

There are two stages when a merge can enter a


conflicted stage.

1. Starting the merge process


Git and GitHub
If there are changes in the working directory of the
stage area in the current project, the merge will fail to
start. In this case, conflicts happen due to pending
changes that need to be stabilized using different Git
commands.

2. During the merge process

The failure during the merge process indicates that


there’s a conflict between the local branch and the
branch being merged. In this case, Git resolves as
much as possible, but some things have to be fixed
manually in the conflicted files.

32. WHAT HAS TO BE RUN TO SQUASH


THE LAST N COMMITS INTO A SINGLE
COMMIT?

In Git, squashing commits means combining two or


more commits into one.

Use the below command to write a new commit


message from the beginning.

git reset -soft HEAD~N &&git commit

But, if you want to edit a new commit message and add


the existing commit messages, then you must extract
the messages and pass them to Git commit.

The below command will help you achieve this:


Git and GitHub
git reset -soft HEAD~N &&git commit -edit -m“$(git log
-format=%B -reverse .HEAD@{N})”

33. WHAT IS THE DIFFERENCE BETWEEN


FORK, BRANCH, AND CLONE?

Fork Branch Clone

Git clone refers


to creating a
The fork is the
clone or a copy
process when a
of an existing git
copy of the
Git branches refer to repository in a
repository is
individual projects new directory.
made. It's usually
within a git Cloning
experimentation
repository. If there automatically
in the project
are several branches creates a
without affecting
in a repository, then connection that
the original
each branch can points back to
project. They’re
have entirely the original
used to advise
different files and repository,
changes or take
folders. which makes it
inspiration from
very easy to
someone else’s
interact with the
project.
central
repository.
Git and GitHub

34. HOW IS GIT MERGE DIFFERENT FROM


GIT REBASE?

Git merge is used to incorporate new commits into your


feature branch.

 Git merge creates an extra merge commit every


time you need to incorporate changes.
 It pollutes your feature branch history.
As an alternative to merging, you can rebase the
feature branch into master.
Git and GitHub

 Git rebase Incorporates all the new commits in


the master branch.
 It rewrites the project history by creating brand
new commits for each commit in the original
branch

35. WHAT IS THE COMMAND USED TO FIX


A BROKEN COMMIT?

To fix a broken commit in Git, you may use the “git


commit --amend” command, which helps you combine
the staged changes with the previous commits instead
of creating an entirely new commit.

36. HOW DO YOU RECOVER A DELETED


BRANCH THAT WAS NOT MERGED?

To recover a deleted branch, first, you can use the git


reflog command. It will list the local recorded logs for
all the references. Then, you can identify the history
stamp and recover it using the git checkout command.
Git and GitHub
37. WHAT IS GIT STASH DROP?

The Git stash drop command is used to remove a


particular stash. If there’s a stash you're no longer
using or you want to remove a specific item of stash
from the list, you can use the stash commands.

Let’s say you want to delete an item named


stash@{abc}; you can use the command:

git stash drop stash@{abc}.

38. WHAT’S THE DIFFERENCE BETWEEN


REVERTING AND RESETTING?

Reverting Resetting

The revert command in Git is used Git reset is a


to create a new commit that undoes command that is
the changes made in the previous used to undo the
commit. When you use this local changes that
command, a new history is added to have been made to a
the project; the existing history is Git repository. Git
not modified. reset operates on the
following: commit
history, the staging
index, and the
Git and GitHub
working directory.

39. HOW CAN YOU DISCOVER IF A


BRANCH HAS ALREADY BEEN MERGED OR
NOT?

There are two commands to determine these two


different things.

git branch --merged - Returns the list of branches that


have been merged into the current branch.

git branch --no-merged - Returns the list of branches


that have not been merged.

40. WHAT IS “GIT CHERRY-PICK”?

The command git cherry-pick enables you to pick up


commits from a branch within a repository and apply it
to another branch. This command is useful to undo
changes when any commit is accidentally made to the
wrong branch. Then, you can switch to the correct
branch and use this command to cherry-pick the
commit.

You might also like