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

Git Tutorial

github tutorial

Uploaded by

shyamsingh841442
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views165 pages

Git Tutorial

github tutorial

Uploaded by

shyamsingh841442
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 165

1) Git config command

This command configures the user. The Git config command is the first
and necessary command used on the Git command line. This command
sets the author name and email address to be used with your commits.
Git config is also used in other scenarios.

Syntax

1. $ git config --global user.name "ImDwivedi1"


2. $ git config --global user.email "Himanshudubey481@gmail.com"

3) Git clone command


This command is used to make a copy of a repository from an existing
URL. If I want a local copy of my repository from GitHub, this command
allows creating a local copy of that repository on your local directory from
the repository URL.

Syntax

1. $ git clone URL

Git Init
The git init command is the first command that you will run on Git. The git
init command is used to create a new blank repository. It is used to make
an existing project as a Git project. Several Git commands run inside the
repository, but init command can be run outside of the repository.

Create a Repository for a Blank (New) Project:


To create a blank repository, open command line on your desired
directory and run the init command as follows:
1. $ git init
Create a Repository and Directory Together
The git init command allows us to create a new blank repository and a
directory together. The empty repository .git is created under the
directory. Suppose I want to create a blank repository with a project
name, then we can do so by the git init command. Consider the below
command:

2 $ git init NewDirectory

The above command will create an empty .git repository under a directory
named NewDirectory.

Git Add
The git add command is used to add file contents to the Index (Staging
Area).This command updates the current content of the working tree to
the staging area. It also prepares the staged content for the next commit.
Every time we add or update any file in our project, it is required to
forward updates to the staging area.

Git add files


Git add command is a straight forward command. It adds files to the
staging area. We can add single or multiple files at once in the staging
area. It will be run as:

1. $ git add <File name>

We have created a file for our newly created repository in NewDirectory.


To create a file, use the touch command as follows:

1. $ touch newfile.txt

And check the status whether it is untracked or not by git status


command as follows:

1. $ git status

The above command will display the untracked files from the repository.
These files can be added to our repository. As we know we have created a
newfile.txt, so to add this file, run the below command:
1. $ git add newfile.txt
Git Add All
We can add more than one files in Git, but we have to run the add
command repeatedly. Git facilitates us with a unique option of the add
command by which we can add all the available files at once. To add all
the files from the repository, run the add command with -A option. We can
use '.' Instead of -A option. This command will stage all the files at a time.
It will run as follows:

1. $ git add -A

Or

1. $ git add .
Git add files
Git add command is a straight forward command. It adds files to the
staging area. We can add single or multiple files at once in the staging
area. It will be run as:

1. $ git add <File name>

The above command is added to the git staging area, but yet it cannot be
shared on the version control system. A commit operation is needed to
share it. Let's understand the below scenario.

We have created a file for our newly created repository in NewDirectory.


To create a file, use the touch command as follows:

1. $ touch newfile.txt

And check the status whether it is untracked or not by git status


command as follows:

1. $ git status

The above command will display the untracked files from the repository.
These files can be added to our repository. As we know we have created a
newfile.txt, so to add this file, run the below command:

1. $ git add newfile.txt

Consider the below output:


From the above output, we can see newfile.txt has been added to our
repository. Now, we have to commit it to share on Git.

Git Add All


We can add more than one files in Git, but we have to run the add
command repeatedly. Git facilitates us with a unique option of the add
command by which we can add all the available files at once. To add all
the files from the repository, run the add command with -A option. We can
use '.' Instead of -A option. This command will stage all the files at a time.
It will run as follows:

1. $ git add -A

Or

1. $ git add .

The above command will add all the files available in the repository.
Consider the below scenario:

We can either create four new files, or we can copy it, and then we add all
these files at once. Consider the below output:
In the above output, all the files are displaying as untracked files by Git.
To track all of these files at once, run the below command:

1. $ git add -A

The above command will add all the files to the staging area. Remember,
the -A option is case sensitive. Consider the below output:

In the above output, all the files have been added. The status of all files is
displaying as staged.
Removing Files from the Staging Area
The git add command is also used to remove files from the staging area. If
we delete a file from the repository, then it is available to our repository
as an untracked file. The add command is used to remove it from the
staging area. It sounds strange, but Git can do it. Consider the below
scenario:

We have deleted the newfile3.txt from the repository. The status of the
repository after deleting the file is as follows:

As we can see from the above output, the deleted file is still available in
the staging area. To remove it from the index, run the below command as
follows:

1. $ git add newfile3.txt

Consider the below output:


From the above output, we can see that the file is removed from the
staging area.

Add all New and Updated Files Only:


Git allows us to stage only updated and newly created files at once. We
will use the ignore removal option to do so. It will be used as follows:

1. $ git add --ignore-removal .


Add all Modified and Deleted Files
Git add facilitates us with a variety of options. There is another option that
is available in Git, which allows us to stage only the modified and deleted
files. It will not stage the newly created file. To stage all modified and
deleted files only, run the below command:

1. $ git add -u
Add Files by Wildcard
Git allows us to add all the same pattern files at once. It is another way to
add multiple files together. Suppose I want to add all java files or text
files, then we can use pattern .java or .txt. To do so, we will run the
command as follows:

1. $ git add *.java

The above command will stage all the Java files. The same pattern will be
applied for the text files.

The next step after adding files is committing to share it on Git.

Git Undo Add


We can undo a git add operation. However, it is not a part of git add
command, but we can do it through git reset command.

To undo an add operation, run the below command:

1. $ git reset <filename>

To learn more about git reset command, visit Git Reset.

Git Commit
It is used to record the changes in the repository. It is the next command
after the git add. Every commit contains the index data and the commit
message. Every commit forms a parent-child relationship. When we add a
file in Git, it will take place in the staging area. A commit command is
used to fetch updates from the staging area to the repository.

The staging and committing are co-related to each other. Staging allows
us to continue in making changes to the repository, and when we want to
share these changes to the version control system, committing allows us
to record these changes.

The git commit command


The commit command will commit the changes and generate a commit-id.
The commit command without any argument will open the default text
editor and ask for the commit message. We can specify our commit
message in this text editor. It will run as follows:

1. $ git commit
Git commit -a
The commit command also provides -a option to specify some commits. It
is used to commit the snapshots of all changes. This option only consider
already added files in Git. It will not commit the newly created files.
Consider below scenario:

We have made some updates to our already staged file newfile3 and
create a file newfile4.txt. Check the status of the repository and run the
commit command as follows:

1. $ git commit -a
it commit -m
The -m option of commit command lets you to write the commit message
on the command line. This command will not prompt the text editor. It will
run as follows:

1. $ git commit -m "Commit message."

We can also use the -am option for already staged files. This command
will immediately make a commit for already staged files with a commit
message. It will run as follows:

1. $ git commit -am "Commit message."


Git Commit Amend (Change commit message)
The amend option lets us to edit the last commit. If accidentally, we have
committed a wrong commit message, then this feature is a savage option
for us. It will run as follows:

1. $ git commit -amend

The above command will prompt the default text editor and allow us to
edit the commit message.

We may need some other essential operations related to commit like


revert commit, undo a commit, and more, but these operations are not a
part of the commit command. We can do it with other commands. Some
essential operations

Git Clone
In Git, cloning is the act of making a copy of any target repository. The
target repository can be remote or local. You can clone your repository
from the remote repository to create a local copy on your system. Also,
you can sync between the two locations.
Git Clone Command
The git clone is a command-line utility which is used to make a local copy
of a remote repository. It accesses the repository through a remote URL.

Usually, the original repository is located on a remote server, often from a


Git service like GitHub, Bitbucket, or GitLab. The remote repository URL is
referred to the origin.

Syntax:

1. $ git clone <repository URL>


Git Clone Branch
Git allows making a copy of only a particular branch from a repository.
You can make a directory for the individual branch by using the git clone
command. To make a clone branch, you need to specify the branch name
with -b command. Below is the syntax of the command to clone the
specific git branch:

Syntax:

1. $ git clone -b <Branch name><Repository URL>

See the below command:

1. $ git clone -b master https://github.com/ImDwivedi1/Git-Example.git


"new folder(2)"
Git Stash
Sometimes you want to switch the branches, but you are working on an
incomplete part of your current project. You don't want to make a commit
of half-done work. Git stashing allows you to do so. The git stash
command enables you to switch branches without committing the
current branch.

The below figure demonstrates the properties and role of stashing


concerning repository and working directory.

Some useful options are given below:

o Git stash
o Git stash save
o Git stash list
o Git stash apply
o Git stash changes
o Git stash pop
o Git stash drop
o Git stash clear
o Git stash branch

Stashing Work
The git stash command is used as:
Syntax:

1. $ git stash

Output:

In the given output, the work is saved with git stash command. We can
check the status of the repository.

As you can see, my work is just stashed in its current position. Now, the
directory is cleaned. At this point, you can switch between branches and
work on them.

Git Stash Save (Saving Stashes with the message):


In Git, the changes can be stashed with a message. To stash a change
with a message, run the below command:

Syntax:

1. $ git stash save "<Stashing Message>"

Output:

The above stash will be saved with a message

Git Stash List (Check the Stored Stashes)


To check the stored stashes, run the below command:

Syntax:

1. $ git stash list


Output:

In the above case, I have made one stash, which is displayed as


"stash@{0}: WIP on the test: 0a1a475 CSS file".

If we have more than one stash, then It will display all the stashes
respectively with different stash id. Consider the below output:

It will show all the stashes with indexing as stash@{0}:


stash@{1}: and so on.

Git Stash Apply


You can re-apply the changes that you just stashed by using the git stash
command. To apply the commit, use the git stash command, followed by
the apply option. It is used as:

Syntax:

1. $ git stash apply

Output:

The above output restores the last stash. Now, if you will check the status
of the repository, it will show the changes that are made on the file.
Consider the below output:
From the above output, you can see that the repository is restored to its
previous state before stash. It is showing output as "Changes not
staged for commit."

In case of more than one stash, you can use "git stash apply" command
followed by stash index id to apply the particular commit. It is used as:

Syntax:

1. $ git stash apply <stash id>

Consider the below output:

Output:

If we don't specify a stash, Git takes the most recent stash and tries to
apply it.

Git Stash Changes


We can track the stashes and their changes. To see the changes in the file
before stash and after stash operation, run the below command:

Syntax:

1. $ git stash show

The above command will show the file that is stashed and changes made
on them. Consider the below output:
Output:

The above output illustrates that there are two files that are stashed, and
two insertions performed on them.

We can exactly track what changes are made on the file. To display the
changed content of the file, perform the below command:

Syntax:

1. $ git stash show -p

Here, -p stands for the partial stash. The given command will show the
edited files and content, consider the below output:

Output:

The above output is showing the file name with changed content. It acts
the same as git diff command. The git diff command will also show the
exact output.
Git Stash Pop (Reapplying Stashed Changes)
Git allows the user to re-apply the previous commits by using git stash
pop command. The popping option removes the changes from stash and
applies them to your working file.

The git stash pop command is quite similar to git stash apply. The main
difference between both of these commands is stash pop command that
deletes the stash from the stack after it is applied.

Syntax:

1. $ git stash pop

The above command will re-apply the previous commits to the repository.
Consider the below output.

Output:

Git Stash Drop (Unstash)


The git stash drop command is used to delete a stash from the queue.
Generally, it deletes the most recent stash. Caution should be taken
before using stash drop command, as it is difficult to undo if once applied.

The only way to revert it is if you do not close the terminal after deleting
the stash. The stash drop command will be used as:

Syntax:

1. $ git stash drop

Output:
In the above output, the most recent stash (stash@{0}) has been
dropped from given three stashes. The stash list command lists all the
available stashes in the queue.

We can also delete a particular stash from the queue. To delete a


particular stash from the available stashes, pass the stash id in stash drop
command. It will be processed as:

Syntax:

1. $ git stash drop <stash id>

Assume that I have two stashes available in my queue, and I don't want to
drop my most recent stash, but I want to delete the older one. Then, it will
be operated as:

1. $ git stash drop stash@{1}

Consider the below output:

In the above output, the commit stash@{1} has been deleted from the
queue.

Git Stash Clear


The git stash clear command allows deleting all the available stashes at
once. To delete all the available stashes, operate below command:
Syntax:

1. $ git stash clear

it will delete all the stashes that exist in the repository.

Output:

All the stashes are deleted in the above output. The git stash list
command is blank because there are no stashes available in the
repository.

Git Stash Branch


If you stashed some work on a particular branch and continue working on
that branch. Then, it may create a conflict during merging. So, it is good
to stash work on a separate branch.

The git stash branch command allows the user to stash work on a
separate branch to avoid conflicts. The syntax for this branch is as follows:

Syntax:

1. $ git stash branch <Branch Name>

The above command will create a new branch and transfer the stashed
work on that. Consider the below output:

Output:
Git Ignore
In Git, the term "ignore" is used to specify intentionally untracked files
that Git should ignore. It doesn't affect the Files that already tracked by
Git.

Sometimes you don't want to send the files to Git service like GitHub. We
can specify files in Git to ignore.

The file system of Git is classified into three categories:

Tracked:

Tracked files are such files that are previously staged or committed.

Untracked:

Untracked files are such files that are not previously staged or committed.

Ignored:

Ignored files are such files that are explicitly ignored by git. We have to
tell git to ignore such files.

Generally, the Ignored files are artifacts and machine-generated files.


These files can be derived from your repository source or should
otherwise not be committed. Some commonly ignored files are as follows:

o dependency caches
o compiled code
o build output directories, like /bin, /out, or /target
o runtime file generated, like .log, .lock, or .tmp
o Hidden system files, like Thumbs.db or.DS_Store
o Personal IDE config files, such as .idea/workspace.xml

Git Ignore Files


Git ignore files is a file that can be any file or a folder that contains all the
files that we want to ignore. The developers ignore files that are not
necessary to execute the project. Git itself creates many system-
generated ignored files. Usually, these files are hidden files. There are
several ways to specify the ignore files. The ignored files can be tracked
on a .gitignore file that is placed on the root folder of the repository. No
explicit command is used to ignore the file.

There is no explicit git ignore command; instead, the .gitignore file must
be edited and committed by hand when you have new files that you wish
to ignore. The .gitignore files hold patterns that are matched against file
names in your repository to determine whether or not they should be
ignored.

How to Ignore Files Manually


There is no command in Git to ignore files; alternatively, there are several
ways to specify the ignore files in git. One of the most common ways is
the .gitignore file. Let's understand it with an example.

The .gitignore file:


Rules for ignoring file is defined in the .gitignore file. The .gitignore file is a
file that contains all the formats and files of the ignored file. We can
create multiple ignore files in a different directory. Let's understand how it
works with an example:

Step1: Create a file named .gitignore if you do not have it already in your
directory. To create a file, use the command touch or cat. It will use as
follows:

1. $ touch .gitignore

Or

1. $ cat .gitignore

The above command will create a .gitignore file on your directory.


Remember, you are working on your desired directory. Consider the below
command:

The above command will create a file named .gitignored. We can track it
on the repository. Consider the below image:
As you can see from the above image, a .gitignore file has been created
for my repository.

Step2: Now, add the files and directories to the .gitignore file that you
want to ignore. To add the files and directory to the .git ignore the file,
open the file and type the file name, directory name, and pattern to
ignore files and directories. Consider the below image:

In the above file, I have given one format and a directory to ignore. The
above format *.txt will ignore all the text files from the repository,
and /newfolder/* will ignore the newfolder and its sub-content. We can
also give only the name of any file to ignore.

Step3: Now, to share it on Git, we have to commit it. The .gitignore file is
still now in staging area; we can track it by git status command. Consider
the below output:
Now to stage it, we have to commit it. To commit it, run the below
command:

1. $ git add .gitignore


2. $ git commit -m "ignored directory created."

The above command will share the file .gitignore on Git. Consider the
below output.

Now, we have ignored a pattern file and a directory in Git.

Rules for putting the pattern in .gitignore file:

The rules for the patterns that can be put in the .gitignore file are as
follows:

o Git ignores the Blank lines or lines starting with #.


o Only the Standard glob patterns work and will be applied recursively
throughout the entire working tree.
o The patterns can be started with a forward slash (/) to avoid recursively.
o The patterns can be ended with a forward slash (/) to specify a directory.
o The patterns can be negated by starting it with an exclamation point (!).

Global .gitignore:.
As we know that we can create multiple .gitignore files for a project. But
Git also allows us to create a universal .gitignore file that can be used for
the whole project. This file is known as a global .gitignore file. To create a
global .gitignore, run the below command on terminal:

1. $ git config --global core.excludesfile ~/.gitignore_global

The above command will create a global .gitignore file for the repository.
How to List the Ignored Files?
In Git, We can list the ignored files. There are various commands to list
the ignored files, but the most common way to list the file is the ls
command. To list the ignored file, run the ls command as follows:

1. $ git ls-files -i --exclude-standard

Or

1. $ git ls-files --ignore --exclude-standard

The above command will list all available ignored files from the repository.
In the given command, -I option stands for ignore and --exclude-
standard is specifying the exclude pattern. Consider the below output:

From the above output, we can see that the ls command is listing the
available ignored files from the repository.

Git Fork
A fork is a rough copy of a repository. Forking a repository allows you to
freely test and debug with changes without affecting the original project.
One of the excessive use of forking is to propose changes for bug fixing.
To resolve an issue for a bug that you found, you can:

o Fork the repository.


o Make the fix.
o Forward a pull request to the project owner.

Forking is not a Git function; it is a feature of Git service like GitHub.


When to Use Git Fork

Generally, forking a repository allows us to experiment on the project


without affecting the original project. Following are the reasons for forking
the repository:

o Propose changes to someone else's project.


o Use an existing project as a starting point.

Let's understand how to fork a repository on GitHub?

How to Fork a Repository?


The forking and branching are excellent ways to contribute to an open-
source project. These two features of Git allows the enhanced
collaboration on the projects.

Forking is a safe way to contribute. It allows us to make a rough copy of


the project. We can freely experiment on the project. After the final
version of the project, we can create a pull request for merging.

It is a straight-forward process. Steps for forking the repository are as


follows:

o Login to the GitHub account.


o Find the GitHub repository which you want to fork.
o Click the Fork button on the upper right side of the repository's page.

We can't fork our own repository. Only shared repositories can be fork. If
someone wants to fork the repository, then he must log in with his
account. Let's understand the below scenario in which a user pune2016
wants to contribute to our project GitExample2. When he searches or put
the address of our repository, our repository will look like as follows:

The above image shows the user interface of my repository from other
contributors. We can see the fork option at the top right corner of the
repository page. By clicking on that, the forking process will start. It will
take a while to make a copy of the project for other users. After the
forking completed, a copy of the repository will be copied to your GitHub
account. It will not affect the original repository. We can freely make
changes and then create a pull request for the main project. The owner of
the project will see your suggestion and decide whether he wants to
merge the changes or not. The fork copy will look like as follows:

As you can see, the forked repository looks like pune2016/GitExample2.


At the bottom of the repository name, we can see a description of the
repository. At the top right corner, the option fork is increased by 1
number.

Hence one can fork the repository from GitHub.

Fork vs. Clone


Sometimes people considered the fork as clone command because of their
property. Both commands are used to create another copy of the
repository. But the significant difference is that the fork is used to create a
server-side copy, and clone is used to create a local copy of the
repository.

There is no particular command for forking the repository; instead, it is a


service provided by third-party Git service like GitHub. Comparatively, git
clone is a command-line utility that is used to create a local copy of the
project.

Generally, people working on the same project clone the repository and
the external contributors fork the repository.

A pull request can merge the changes made on the fork repository. We
can create a pull request to propose changes to the project.
Comparatively, changes made on the cloned repository can be merged by
pushing. We can push the changes to our remote repository.
Git Repository
In Git, the repository is like a data structure used by VCS to store
metadata for a set of files and directories. It contains the collection of the
files as well as the history of changes made to those files. Repository in
Git is considered as your project folder. A repository has all the project-
related data. Distinct projects have distinct repositories.

Getting a Git Repository


There are two ways to obtain a repository. They are as follows:
o Create a local repository and make it as Git repository.
o Clone a remote repository (already exists on a server).

In either case, you can start working on a Git repository.

Initializing a Repository
If you want to share your project on a version control system and control it
with Git. Then, browse your project's directory and start the git command
line (Git Bash for Windows) here. To initialize a new repository, run the
below command:

Syntax:

1. $ git init

Output:

The above command will create a new subdirectory named .git that holds
all necessary repository files. The .git subdirectory can be understood as
a Git repository skeleton. Consider the below image:

An empty repository .git is added to my existing project. If we want to


start version-controlling for existing files, we should track these files with
git add command, followed by a commit.

We can list all the untracked files by git status command.


1. $ git status
Consider the below output:

In the above output, the list of all untracked files is displayed by the git
status command. To share these files on the version control system, we
have to track it with git add command followed by a commit. To track the
files, operate git add command as follows:

Syntax:

1. $ git add <filename>

To commit a file, perform the git commit command as follows:

1. $ git commit -m "Commit message."

Output:
In the above output, I have added three of my existing files by git add
command and commit it for sharing.

We can also create new files. To share the new file, follow the same
procedure as described above; add and commit it for sharing. Now, you
have a repository to share.

Cloning an Existing Repository


We can clone an existing repository. Suppose we have a repository on a
version control system like subversion, GitHub, or any other remote
server, and we want to share it with someone to contribute. The git clone
command will make a copy for any user to contribute.

We can get nearly all data from server with git clone command. It can be
done as:

Syntax:

1. $ git clone <Repository URL>


Suppose one of my friends has a repository on my GitHub account, and I
want to contribute to it. So the first thing I will do, make a copy of this
project to my local system for a better work interface. The essential
element needed for cloning the repository URL. I have a repository URL
"https://github.com/ImDwivedi1/Git-Example". To clone this repository,
operate the clone command as:

1. $ git clone https://github.com/ImDwivedi1/Git-Example

Consider the below output:


In the above output, the repository Git-Example has been cloned. Now this
repository is available on your local storage. You can commit it and
contribute to the project by pushing it on a remote server.

A single repository can be cloned any number of times. So we can clone a


repository on various locations and various systems.

Git Index
The Git index is a staging area between the working directory and
repository. It is used to build up a set of changes that you want to commit
together. To better understand the Git index, then first understand the
working directory and repository.
There are three places in Git where file changes can reside, and these are
working directory, staging area, and the repository. To better understand
the Git index first, let's take a quick view of these places.

Working directory:
When you worked on your project and made some changes, you are
dealing with your project's working directory. This project directory is
available on your computer's filesystem. All the changes you make will
remain in the working directory until you add them to the staging area.

Staging area:
The staging area can be described as a preview of your next commit.
When you create a git commit, Git takes changes that are in the staging
area and make them as a new commit. You are allowed to add and
remove changes from the staging area. The staging area can be
considered as a real area where git stores the changes.

Although, Git doesn't have a dedicated staging directory where it can


store some objects representing file changes (blobs). Instead of this, it
uses a file called index.

Repository:
In Git, Repository is like a data structure used by GIt to store metadata for
a set of files and directories. It contains the collection of the files as well
as the history of changes made to those files. Repositories in Git is
considered as your project folder. A repository has all the project-related
data. Distinct projects have distinct repositories.
You can check what is in the index by the git status command. The git
status command allows you to see which files are staged, modified but not
yet staged, and completely untracked. Staged files mean, it is currently in
the index. See the below example.

Syntax:

1. $ git status

Output:

In the given output, the status command shows the index.

As we mentioned earlier index is a file, not a directory, So Git is not


storing objects into it. Instead, it stores information about each file in our
repository. This information could be:

o mtime: It is the time of the last update.


o file: It is the name of the file.
o Wdir: The version of the file in the working directory.
o Stage: The version of the file in the index.
o Repo: The version of the file in the repository.

And finally, Git creates your working directory to match the content of the
commit that HEAD is pointing.
Git Head
The HEAD points out the last commit in the current checkout branch. It is
like a pointer to any reference. The HEAD can be understood as the
"current branch." When you switch branches with 'checkout,' the HEAD
is transferred to the new branch.

The above fig shows the HEAD referencing commit-1 because of a


'checkout' was done at commit-1. When you make a new commit, it shifts
to the newer commit. The git head command is used to view the status of
Head with different arguments. It stores the status of Head in .git\refs\
heads directory. Let's see the below example:
Git Show Head
The git show head is used to check the status of the Head. This
command will show the location of the Head.

Syntax:

1. $ git show HEAD

Output:

In the above output, you can see that the commit id for the Head is given.
It means the Head is on the given commit.

Now, check the commit history of the project. You can use the git log
command to check the commit history. See the below output:

As we can see in the above output, the commit id for most recent commit
and Head is the same. So, it is clear that the last commit has the Head.
We can also check the status of the Head by the commit id. Copy the
commit id from the above output and paste it with the git
show command. Its result is same as git show head command if the
commit id is last commit's id. See the below output:

The above output is the same as git show output.

The HEAD is capable of referring to a specific revision that is not associated with
a branch name. This situation is called a detached HEAD.

Git Detached Head


GitHub keeps track of all commits or snapshots over time. If you check the
'git log' in your terminal, you can show all the previous commits up to the
first commit. Detached HEAD mode allows you to discover an older state
of a repository. It is a natural state in Git.

When Head doesn't point to most recent commit, such state is


called detached Head. If you checkout with an older commit, it will
stand the detached head condition. See the below example:
I have copied the older commit id. Now I will check out with this id.

As you can see in the given example, Head does not point the most recent
commit. It is called a detached head state. It is always recommended, do
not commit on detached Head.
Git Origin Master
The term "git origin master" is used in the context of a remote repository.
It is used to deal with the remote repository. The term origin comes from
where repository original situated and master stands for the main branch.
Let's understand both of these terms in detail.

Git Master
Master is a naming convention for Git branch. It's a default branch of Git.
After cloning a project from a remote server, the resulting local repository
contains only a single local branch. This branch is called a "master"
branch. It means that "master" is a repository's "default" branch.

In most cases, the master is referred to as the main branch. Master


branch is considered as the final view of the repo. Your local repository
has its master branch that always up to date with the master of a remote
repository.

Do not mess with the master. If you edited the master branch of a group
project, your changes will affect everyone else and very quickly there will
be merge conflicts.

Git Origin
In Git, The term origin is referred to the remote repository where you want
to publish your commits. The default remote repository is called origin,
although you can work with several remotes having a different name at
the same time. It is said as an alias of the system.

The origin is a short name for the remote repository that a project was
initially being cloned. It is used in place of the original repository URL.
Thus, it makes referencing much easier.

Origin is just a standard convention. Although it is significant to leave this


convention untouched, you could ideally rename it without losing any
functionality.

In the following example, the URL parameter acts as an origin to the


"clone" command for the cloned local repository:

1. $ git clone https://github.com/ImDwivedi1/Git-Example

Some commands in which the term origin and master are widely used are
as follows:

o Git push origin master


o Git pull origin master

Git has two types of branches called local and remote. To use git pull and
git push, you have to tell your local branch that on which branch is going
to operate. So, the term origin master is used to deal with a remote
repository and master branch. The term push origin master is used to
push the changes to the remote repository. The term pull origin
master is used to access the repository from remote to local.
Git Remote
In Git, the term remote is concerned with the remote repository. It is a
shared repository that all team members use to exchange their changes.
A remote repository is stored on a code hosting service like an internal
server, GitHub, Subversion, and more. In the case of a local repository, a
remote typically does not provide a file tree of the project's current state;
as an alternative, it only consists of the .git versioning data.

The developers can perform many operations with the remote server.
These operations can be a clone, fetch, push, pull, and more. Consider the
below image:
Check your Remote
To check the configuration of the remote server, run the git
remote command. The git remote command allows accessing the
connection between remote and local. If you want to see the original
existence of your cloned repository, use the git remote command. It can
be used as:

Syntax:

1. $ git remote

Output:

The given command is providing the remote name as the origin. Origin is
the default name for the remote server, which is given by Git.

Git remote -v:

Git remote supports a specific option -v to show the URLs that Git has
stored as a short name. These short names are used during the reading
and write operation. Here, -v stands for verbose. We can use --
verbose in place of -v. It is used as:

Syntax:

1. $ git remote -v
Or

1. $ git remote --verbose

Output:

The above output is providing available remote connections. If a


repository contains more than one remote connection, this command will
list them all.

Git Remote Add


When we fetch a repository implicitly, git adds a remote for the repository.
Also, we can explicitly add a remote for a repository. We can add a remote
as a shot nickname or short name. To add remote as a short name, follow
the below command:

Syntax:

1. $ git remote add <short name><remote URL>

Output:
In the above output, I have added a remote repository with an existing
repository as a short name "hd". Now, you can use "hd" on the command
line in place of the whole URL. For example, you want to pull the
repository, consider below output:

I have pulled a repository using its short name instead of its remote URL.
Now, the repository master branch can be accessed through a short
name.

Fetching and Pulling Remote Branch


You can fetch and pull data from the remote repository. The fetch and pull
command goes out to that remote server, and fetch all the data from that
remote project that you don't have yet. These commands let us fetch the
references to all the branches from that remote.

To fetch the data from your remote projects, run the below command:

1. $ git fetch <remote>


To clone the remote repository from your remote projects, run the below
command:

1. $ git clone<remote>

When we clone a repository, the remote repository is added by a default


name "origin." So, mostly, the command is used as git fetch origin.

The git fetch origin fetches the updates that have been made to the
remote server since you cloned it. The git fetch command only downloads
the data to the local repository; it doesn't merge or modify the data until
you don't operate. You have to merge it manually into your repository
when you want.
To pull the repository, run the below command:

1. $ git pull <remote>

The git pull command automatically fetches and then merges the remote
data into your current branch. Pulling is an easier and comfortable
workflow than fetching. Because the git clone command sets up your local
master branch to track the remote master branch on the server you
cloned.

Pushing to Remote Branch


If you want to share your project, you have to push it upstream. The git
push command is used to share a project or send updates to the remote
server. It is used as:

1. $ git push <remote><branch>

To update the main branch of the project, use the below command:

1. $ git push origin master

It is a special command-line utility that specifies the remote branch and


directory. When you have multiple branches on a remote server, then this
command assists you to specify your main branch and repository.

Generally, the term origin stands for the remote repository, and master is
considered as the main branch. So, the entire statement "git push origin
master" pushed the local content on the master branch of the remote
location.

Git Remove Remote


You can remove a remote connection from a repository. To remove a
connection, perform the git remote command with remove or rm option.
It can be done as:

Syntax:

1. $ git remote rm <destination>

Or

1. $ git remote remove <destination>

Consider the below example:


Suppose you are connected with a default remote server "origin." To
check the remote verbosely, perform the below command:

1. $ git remote -v

Output:

The above output will list the available remote server. Now, perform the
remove operation as mentioned above. Consider the below output:

In the above output, I have removed remote server "origin" from my


repository.

Git Remote Rename


Git allows renaming the remote server name so that you can use a short
name in place of the remote server name. Below command is used to
rename the remote server:

Syntax:

1. $ git remote rename <old name><new name>

Output:
In the above output, I have renamed my default server name origin to hd.
Now, I can operate using this name in place of origin. Consider the below
output:

In the above output, I have pulled the remote repository using the server
name hd. But, when I am using the old server name, it is throwing an error
with the message "'origin' does not appear to be a git repository." It
means Git is not identifying the old name, so all the operations will be
performed by a new name.

Git Show Remote


To see additional information about a particular remote, use the git
remote command along with show sub-command. It is used as:

Syntax:

1. $ git remote show <remote>

It will result in information about the remote server. It contains a list of


branches related to the remote and also the endpoints attached for
fetching and pushing.

Output:
The above output is listing the URLs for the remote repository as well as
the tracking branch information. This information will be helpful in various
cases.

Git Change Remote (Changing a Remote's URL)


We can change the URL of a remote repository. The git remote set
command is used to change the URL of the repository. It changes an
existing remote repository URL.

Git Remote Set:

We can change the remote URL simply by using the git remote set
command. Suppose we want to make a unique name for our project to
specify it. Git allows us to do so. It is a simple process. To change the
remote URL, use the below command:

1. $ git remote set-url <remote name><newURL>

The remote set-url command takes two types of arguments. The first
one is <remote name >, it is your current server name for the repository.
The second argument is <newURL>, it is your new URL name for the
repository. The <new URL> should be in below
format: https://github.com/URLChanged

Consider the below image:


In the above output, I have changed my existing repository URL
as https://github.com/URLChanged from https://github.com/ImDwiv
edi1/GitExample2. It can be understood by my URL name that I have
changed this. To check the latest URL, perform the below command:

1. $ git remote -v

Git Tags
Tags make a point as a specific point in Git history. Tags are used to mark
a commit stage as relevant. We can tag a commit for future reference.
Primarily, it is used to mark a project's initial point like v1.1.

Tags are much like branches, and they do not change once initiated. We
can have any number of tags on a branch or different branches. The
below figure demonstrates the tags on various branches.
In the above image, there are many versions of a branch. All these
versions are tags in the repository.

There are two types of tags.

o Annotated tag
o Light-weighted tag

Both of these tags are similar, but they are different in case of the amount
of Metadata stores.

When to create a Tag:


o When you want to create a release point for a stable version of your code.
o When you want to create a historical point that you can refer to reuse in
the future.

Git Create tag


To create a tag first, checkout to the branch where you want to create a
tag. To check out the branch, run the below command:

1. $ git checkout <Branch name>

Now, you are on your desired branch, say, master. Consider the below
output:
You can create a tag by using the git tag command. Create a tag with
some name say v1.0, v1.1, or any other name whatever you want. To
create a tag, run the command as follows:

Syntax:

1. $ git tag <tag name>


The above command will mark the current status of the project. Consider
the below example:

1. $ git tag projectv1.0

The above command will create a mark point on the master branch
as projectv1.0.

Git List Tag


We can list the available tags in our repository. There are three options
that are available to list the tags in the repository. They are as follows:

o git tag
o git show
o git tag -l ".*"

The "git tag":


It is the most generally used option to list all the available tags from the
repository. It is used as:

1. $ git tag

Output:
As we can see from the above output, the git tag command is listing the
available tags from the repository.

The git tag show <tagname>:


It's a specific command used to display the details of a particular tag. It is
used as:

Syntax:

1. $ git tag show <tagname>

The above command will display the tag description, consider the below
command:

1. $ git tag show projectv1.0

Output:

In the above output, the git show tag is displaying the description of
tag projectv1.0, such as author name and date.

The git tag -l ".*":


It is also a specific command-line tool. It displays the available tags using
wild card pattern. Suppose we have ten tags as v1.0, v1.1, v1.2 up to
v1.10. Then, we can list all v pattern using tag pattern v. it is used as:

Syntax:

1. $ git tag -l "<pattern>.*"


The above command will display all the tags that contain wild card
characters. Consider the below command:

1. $ git tag -l "pro*"


Output:

The above command is displaying a list of the tags that started with a
word pro.

Types of Git tags


There are two types of tags in git. They are as:

o Annotated tag
o Light-weighted tag

Let's understand both of these tags in detail.

Annotated Tags
Annotated tags are tags that store extra Metadata like developer name,
email, date, and more. They are stored as a bundle of objects in the Git
database.

If you are pointing and saving a final version of any project, then it is
recommended to create an annotated tag. But if you want to make a
temporary mark point or don't want to share information, then you can
create a light-weight tag. The data provided in annotated tags are
essential for a public release of the project. There are more options
available to annotate, like you can add a message for annotation of the
project.

To create an annotated tag, run the below command:

Syntax:

1. $ git tag <tag name> -m "< Tag message>

The above command will create a tag with a message. Annotated tags
contain some additional information like author name and other project
related information. Consider the below image:
The above command will create an annotated tag projectv1.1 in the
master branch of my project's repository.

When we display an annotated tag, it will show more information about


tag. Consider the below output:

Light-Weighted Tag:
Git supports one more type of tag; it is called as Light-weighted tag. The
motive of both tags is the same as marking a point in the repository.
Usually, it is a commit stored in a file. It does not store unnecessary
information to keep it light-weight. No command-line option such as -a,-
s or -m are supplied in light-weighted tag, pass a tag name.

Syntax:

1. $ git tag <tag name>

The above command will create a light-weight tag. Consider the below
example:

1. $ git tag projectv1.0

The given output will create a light-weight tag named projectv1.0.

It will display a reduced output than an annotated tag. Consider the below
output:
Git Push Tag
We can push tags to a remote server project. It will help other team
members to know where to pick an update. It will show as release
point on a remote server account. The git push command facilitates with
some specific options to push tags. They are as follows:

o Git push origin <tagname>


o Git push origin -tags/ Git push --tags

The git push origin :


We can push any particular tag by using the git push command. It is used
as follows:

Syntax:

1. $ git push origin <tagname>

The above command will push the specified tag name as a release point.
Consider the below example:

I have created some tags in my local repository, and I want to push it on


my GitHub account. Then, I have to operate the above command.
Consider the below image; it is my remote repository current status.

The above image is showing the release point as 0 releases. Now,


perform the above command. Consider the below output:
I have pushed my projectv1.0 tag to the remote repository. It will change
the repository's current status. Consider the below image:

By refreshing the repository, it is showing release point as 1 release. We


can see this release by clicking on it. It will show as:

We can download it as a zip and tar file.

The git push origin --tag/ git push --tags:


The given command will push all the available tags at once. It will create
as much release point as the number of tags available in the repository. It
is used as follows:

Syntax:

1. $ git push origin --tags

Or

1. $ git push --tags


The above command will push all the available tags from the local
repository to the remote repository. Consider the below output:

Output:

Tags have been pushed to remote server origin; thus, the release point is
also updated. Consider the below snapshot of the repository:

The release point is updated in the above output according to tags. You
can see that releases updated as 2 releases.

Git Delete Tag


Git allows deleting a tag from the repository at any moment. To delete a
tag, run the below command:

Syntax:

1. $git tag --d <tagname>

Or

1. $ git tag --delete <tagname>


The above command will delete a particular tag from the local repository.
Suppose I want to delete my tag projectv1.0 then the process will be as:

1. $ git tag --d projectv1.0


Consider below output:

The tag projectv1.0 has been deleted from the repository.

Delete a Remote Tag:


We can also delete a tag from the remote server. To delete a tag from the
remote server, run the below command:

Syntax:

1. $ git push origin -d <tagname>

Or

1. $ git push origin --delete<tag name>

The above command will delete the specified tag from the remote server.
Consider the below output:

The projectv1.0 tag has been deleted from the remote server origin.

Delete Multiple Tags:


We can delete more than one tag just from a single command. To delete
more than one tag simultaneously, run the below command:

Syntax:

1. $ git tag -d <tag1> <tag2>


Output:

The above command will delete both the tags from the local repository.

We can also delete multiple tags from the remote server. To delete tags
from the server origin, run the below command:

1. $ git push origin -d <tag1> <tag2>

The above command will delete both tags from the server.

Git Checkout Tags


There is no actual concept of check out the tags in git. However, we can
do it by creating a new branch from a tag. To check out a tag, run the
below command:

Syntax:

1. $ git checkout -b < new branch name> <tag name>

The above command will create a new branch with the same state of the
repository as it is in the tag. Consider the below output:

The above command will create a new branch and transfer the status of
the repository to new_branchv1.1 as it is on tag projectv1.1.

Create a tag from an older commit:

If you want to go back to your history and want to create a tag on that
point. Git allows you to do so. To create a tag from an older commit, run
the below command:

1. < git tag <tagname> < reference of commit>

In the above command, it is not required to give all of the 40 digit


number; you can give a part of it.

Suppose I want to create a tag for my older commit, then the process will
be as follows:

Check the older commits:


To check the older commit, run the git status command. It will operate as
follows:

1. $ git status

Consider the below output:

The above output is showing the older commits. Suppose I want to create
a tag for my commit, starting with 828b9628. Copy the particular
reference of the commit. And pass it as an argument in the above
command. Consider the below output:
Upstream and Downstream
The term upstream and downstream refers to the repository. Generally,
upstream is from where you clone the repository, and downstream is any
project that integrates your work with other works. However, these terms
are not restricted to Git repositories.

There are two different contexts in Git for upstream/downstream, which


are remotes and time/history. In the reference of remote
upstream/downstream, the downstream repo will be pulled from the
upstream repository. Data will flow downstream naturally.

In the reference of time/history, it can be unclear, because upstream in


time means downstream in history, and vice-versa. So it is better if we use
the parent/child terms in place of upstream/downstream in case of
time/history.

Git set-upstream
The git set-upstream allows you to set the default remote branch for your
current local branch. By default, every pull command sets the master as
your default remote branch.

Sometimes we are trying to push some changes to the remote server, but
it will show the error like "error: failed to push some refs to 'https :<
remote repository Address>." There may be the reason that you have
not set your remote branch. We can set the remote branch for the local
branch. We will implement the following process to set the remote server:

To check the remote server, use the below command:

1. $ git remote -v

It will result as follows:


The above output is displaying the remote server name. To better
understand remote server, Click here. Now, check the available branches,
run the below command:

1. $ git branch -a

It will result as follows:

The above command will list the branches on the local and remote
repository. To learn more about branches, click here. Now push the
changes to remote server and set the particular branch as default remote
branch for the local repository. To push the changes and set the remote
branch as default, run the below command:

1. $ git push --set-upstream origin master

The above command will set the master branch as the default remote
branch. To better understand the origin master click here.

Consider the below output:

In the given output, everything is up to date with the remote branch.

We can also set the default remote branch by using the git branch
command. To do so, run the below command:

1. $ git branch --set-upstream-to origin master

To display default remote branches, run the below command:

1. $ git branch -vv

Consider the below output:


The above output is displaying the branches available on the repository.
We can see that the default remote branch is specified by highlighted
letters.

Git Checkout
In Git, the term checkout is used for the act of switching between different
versions of a target entity. The git checkout command is used to switch
between branches in a repository. Be careful with your staged files and
commits when switching between branches.

The git checkout command operates upon three different entities which
are files, commits, and branches. Sometimes this command can be
dangerous because there is no undo option available on this command.
It checks the branches and updates the files in the working directory to
match the version already available in that branch, and it forwards the
updates to Git to save all new commit in that branch.

Operations on Git Checkout


We can perform many operations by git checkout command like the
switch to a specific branch, create a new branch, checkout a remote
branch, and more. The git branch and git checkout commands can be
integrated.

Checkout Branch
You can demonstrate how to view a list of available branches by executing
the git branch command and switch to a specified branch.

To demonstrate available branches in repository, use the below


command:

1. $ git branch

Now, you have the list of available branches. To switch between branches,
use the below command.

Syntax:

1. $ git checkout <branchname>

Output:

As you can see in the given output that master branch has switched to
TestBranch.

Create and Switch Branch


The git checkout commands let you create and switch to a new branch.
You can not only create a new branch but also switch it simultaneously by
a single command. The git checkout -b option is a convenience flag that
performs run git branch <new-branch>operation before running git
checkout <new-branch>.

Syntax:

1. $ git checkout -b <branchname>

Output:

As you can see in the given output, branch3 is created and switched from
the master branch.

Checkout Remote Branch


Git allows you to check out a remote branch by git checkout command. It
is a way for a programmer to access the work of a colleague or
collaborator for review and collaboration. Each remote repository contains
its own set of branches. So, to check out a remote branch, you have first
to fetch the contents of the branch.

1. $ git fetch --all

In the latest versions of Git, you can check out the remote branch like a
local branch.

Syntax:

1. $ git checkout <remotebranch>

Output:
In the above output, first, the fetch command is executed to fetch the
remote data; after that, the checkout command is executed to check out a
remote branch.

Edited is my remote branch. Here, we have switched to edited branch


from master branch by git command line.

The earlier versions of Git require the creation of a new branch based on
the remote. In earlier versions, below command is used to check out the
remote branch.

1. $ git checkout <remotebranch> origin/<remotebranch>

Git Revert
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. To undo the changes, run the
below command:

Syntax:

1. $ git revert
Git Revert Options:
Git revert allows some additional operations like editing, no editing,
cleanup, and more. Let's understand these options briefly:

< commit>: The commit option is used to revert a commit. To revert a


commit, we need the commit reference id. The git log command can
access it.

1. $ git revert <commit-ish>

<--edit>: It is used to edit the commit message before reverting the


commit. It is a default option in git revert command.

1. $ git revert -e <commit-ish>

-m parent-number /--mainline parent-number: it is used to revert the


merging. Generally, we cannot revert a merge because we do not know
which side of the merge should be considered as the mainline. We can
specify the parent number and allows revert to reverse the change
relative to the specified parent.

-n/--no edit: This option will not open a text editor. It will directly revert
the last commit.

1. $ git revert -n <commit-ish>

--cleanup=<mode>: The cleanup option determines how to strip spaces


and comments from the message.

-n/--no-commit: Generally, the revert command commits by default. The


no-commit option will not automatically commit. In addition, if this option
is used, your index does not have to match the HEAD commit.
The no-commit option is beneficial for reverting more than one commits
effect to your index in a row.

Let's understand how to revert the previous commits.

Git Revert to Previous Commit


Suppose you have made a change to a file say newfile2.txt of your
project. And later, you remind that you have made a wrong commit in the
wrong file or wrong branch. Now, you want to undo the changes you can
do so. Git allows you to correct your mistakes. Consider the below image:

As you can see from the above output that I have made changes in
newfile2.txt. We can undo it by git revert command. To undo the changes,
we will need the commit-ish. To check the commit-ish, run the below
command:

1. $ git log

Consider the below output:


In the above output, I have copied the most recent commit-ish to revert.
Now, I will perform the revert operation on this commit. It will operate as:

1. $ git revert 099a8b4c8d92f4e4f1ecb5d52e09906747420814

The above command will revert my last commit. Consider the below
output:

As you can see from the above output, the changes made on the
repository have been reverted.

Git Revert Merge


In Git, merging is also a commit that has at least two parents. It connects
branches and code to create a complete project.

A merge in Git is a commit that has at least two parents. It brings together
multiple lines of development. In a work-flow where features are
developed in branches and then merged into a mainline, the merge
commits would typically have two parents.
How to Revert a Merge
Usually, reverting a merge considered a complicated process. It can be
complex if not done correctly. We are going to undo a merge operation
with the help of git revert command. Although some other commands like
git reset can do it. Let's understand how to revert a merge. Consider the
below example.

I have made some changes to my file design2.css on the test and merge
it with test2. Consider the below output:

To revert a merge, we have to get its reference number. To check commit


history, run the below command:

1. $ git log

The above command will display the commit history. Consider the below
output:

From the above output, copy your merging commit that you to want to
revert and run the below command:
1. $ git revert <commit reference> -m 1

The above command will revert the merging operation. Here, -m 1 is used
for the first parent as the mainline. Merge commit has multiple parents.
The revert needs additional information to decide which parent of the
merge shall be considered as the mainline. In such cases, the parameter -
m is used. Consider the below output:

From the above output, we can see that the previous merge has been
reverted.

Git Revert
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. To undo the changes, run the
below command:

Syntax:

1. $ git revert
Git Revert Options:
Git revert allows some additional operations like editing, no editing,
cleanup, and more. Let's understand these options briefly:
< commit>: The commit option is used to revert a commit. To revert a
commit, we need the commit reference id. The git log command can
access it.

1. $ git revert <commit-ish>

<--edit>: It is used to edit the commit message before reverting the


commit. It is a default option in git revert command.

1. $ git revert -e <commit-ish>

-m parent-number /--mainline parent-number: it is used to revert the


merging. Generally, we cannot revert a merge because we do not know
which side of the merge should be considered as the mainline. We can
specify the parent number and allows revert to reverse the change
relative to the specified parent.

-n/--no edit: This option will not open a text editor. It will directly revert
the last commit.

1. $ git revert -n <commit-ish>

--cleanup=<mode>: The cleanup option determines how to strip spaces


and comments from the message.

-n/--no-commit: Generally, the revert command commits by default. The


no-commit option will not automatically commit. In addition, if this option
is used, your index does not have to match the HEAD commit.

The no-commit option is beneficial for reverting more than one commits
effect to your index in a row.

Let's understand how to revert the previous commits.

Git Revert to Previous Commit


Suppose you have made a change to a file say newfile2.txt of your
project. And later, you remind that you have made a wrong commit in the
wrong file or wrong branch. Now, you want to undo the changes you can
do so. Git allows you to correct your mistakes. Consider the below image:
As you can see from the above output that I have made changes in
newfile2.txt. We can undo it by git revert command. To undo the changes,
we will need the commit-ish. To check the commit-ish, run the below
command:

1. $ git log

Consider the below output:


In the above output, I have copied the most recent commit-ish to revert.
Now, I will perform the revert operation on this commit. It will operate as:

1. $ git revert 099a8b4c8d92f4e4f1ecb5d52e09906747420814

The above command will revert my last commit. Consider the below
output:

As you can see from the above output, the changes made on the
repository have been reverted.

Git Revert Merge


In Git, merging is also a commit that has at least two parents. It connects
branches and code to create a complete project.

A merge in Git is a commit that has at least two parents. It brings together
multiple lines of development. In a work-flow where features are
developed in branches and then merged into a mainline, the merge
commits would typically have two parents.

How to Revert a Merge


Usually, reverting a merge considered a complicated process. It can be
complex if not done correctly. We are going to undo a merge operation
with the help of git revert command. Although some other commands like
git reset can do it. Let's understand how to revert a merge. Consider the
below example.

I have made some changes to my file design2.css on the test and merge
it with test2. Consider the below output:

To revert a merge, we have to get its reference number. To check commit


history, run the below command:

1. $ git log
The above command will display the commit history. Consider the below
output:

From the above output, copy your merging commit that you to want to
revert and run the below command:

1. $ git revert <commit reference> -m 1

The above command will revert the merging operation. Here, -m 1 is used
for the first parent as the mainline. Merge commit has multiple parents.
The revert needs additional information to decide which parent of the
merge shall be considered as the mainline. In such cases, the parameter -
m is used. Consider the below output:

From the above output, we can see that the previous merge has been
reverted.
Git Reset
The term reset stands for undoing changes. The git reset command is
used to reset the changes. The git reset command has three core forms of
invocation. These forms are as follows.

o Soft
o Mixed
o Hard

If we say in terms of Git, then Git is a tool that resets the current state of
HEAD to a specified state. It is a sophisticated and versatile tool for
undoing changes. It acts as a time machine for Git. You can jump up
and forth between the various commits. Each of these reset variations
affects specific trees that git uses to handle your file in its content.

Additionally, git reset can operate on whole commits objects or at an


individual file level. Each of these reset variations affects specific trees
that git uses to handle your file and its contents.
Git uses an index (staging area), HEAD, and working directory for creating
and reverting commits. If you have no idea about what is Head, trees,
index, then do visit here Git Index and Git Head.

The working directory lets you change the file, and you can stage into the
index. The staging area enables you to select what you want to put into
your next commit. A commit object is a cryptographically hashed version
of the content. It has some Metadata and points which are used to switch
on the previous commits.

Let's understand the different uses of the git reset command.

Git Reset Hard


It will first move the Head and update the index with the contents of the
commits. It is the most direct, unsafe, and frequently used option. The --
hard option changes the Commit History, and ref pointers are updated to
the specified commit. Then, the Staging Index and Working Directory need
to reset to match that of the specified commit. Any previously pending
commits to the Staging Index and the Working Directory gets reset to
match Commit Tree. It means any awaiting work will be lost.

Let's understand the --hard option with an example. Suppose I have added
a new file to my existing repository. To add a new file to the repository,
run the below command:
1. $ git add <file name>

To check the status of the repository, run the below command:

1. $ git status

To check the status of the Head and previous commits, run the below
command:

1. $ git log

Consider the below image:

In the above output, I have added a file named newfile2.txt. I have


checked the status of the repository. We can see that the current head
position yet not changed because I have not committed the changes.
Now, I am going to perform the reset --hard option. The git reset hard
command will be performed as:

1. $ git reset --hard

Consider the below output:


As you can see in the above output, the -hard option is operated on the
available repository. This option will reset the changes and match the
position of the Head before the last changes. It will remove the available
changes from the staging area. Consider the below output:

The above output is displaying the status of the repository after the hard
reset. We can see there is nothing to commit in my repository because all
the changes removed by the reset hard option to match the status of the
current Head with the previous one. So the file newfile2.txt has been
removed from the repository.

There is a safer way to reset the changes with the help of git stash.

Generally, the reset hard mode performs below operations:

o It will move the HEAD pointer.


o It will update the staging Area with the content that the HEAD is pointing.
o It will update the working directory to match the Staging Area.

Git Reset Mixed


A mixed option is a default option of the git reset command. If we would
not pass any argument, then the git reset command considered as --
mixed as default option. A mixed option updates the ref pointers. The
staging area also reset to the state of a specified commit. The undone
changes transferred to the working directory. Let's understand it with an
example.

Let's create a new file say newfile2.txt. Check the status of the
repository. To check the status of the repository, run the below command:

1. $ git status

It will display the untracked file from the staging area. Add it to the index.
To add a file into stage index, run the git add command as:

1. $ git add <filename>

The above command will add the file to the staging index. Consider the
below output:
In the above output, I have added a newfile2.txt to my local repository.
Now, we will perform the reset mixed command on this repository. It will
operate as:

1. $ git reset --mixed

Or we can use only git reset command instead of this command.

1. $ git reset

The above command will reset the status of the Head, and it will not
delete any data from the staging area to match the position of the Head.
Consider the below output:

From the above output, we can see that we have reset the position of the
Head by performing the git reset -mixed command. Also, we have
checked the status of the repository. As we can see that the status of the
repository has not been changed by this command. So it is clear that the
mixed-mode does not clear any data from the staging area.

Generally, the reset mixed mode performs the below operations:

o It will move the HEAD pointer


o It will update the Staging Area with the content that the HEAD is pointing
to.
It will not update the working directory as git hard mode does. It will only
reset the index but not the working tree, then it generates the report of
the files which have not been updated.

If -N is specified on the command line, then the statements will be


considered as intent-to-add by Git.

Git Reset Head (Git Reset Soft)


The soft option does not touch the index file or working tree at all, but it
resets the Head as all options do. When the soft mode runs, the refs
pointers updated, and the resets stop there. It will act as git amend
command. It is not an authoritative command. Sometimes developers
considered it as a waste of time.

Generally, it is used to change the position of the Head. Let's understand


how it will change the position of the Head. It will use as:

1. $ git reset--soft <commit-sha>

The above command will move the HEAD to the particular commit. Let's
understand it with an example.

I have made changes in my file newfile2.txt and commit it. So, the current
position of Head is shifted on the latest commit. To check the status of
Head, run the below command:

1. $ git log

Consider the below output:


From the above output, you can see that the current position of the HEAD
is on f1d4b486f2eeefe575194d51ec3a54926ab05ef7 commit. But, I want
to switch it on my older commit
2c5a8820091654ac5b8beed774fe6061954cfe92. Since the commit-sha
number is a unique number that is provided by sha algorithm. To switch
the HEAD, run the below command:

1. $ git reset --soft 2c5a8820091654

The above command will shift my HEAD to a particular commit. Consider


the below output:

As you can see from the above output, the HEAD has been shifted to a
particular commit by git reset --soft mode.

Git Reset to Commit


Sometimes we need to reset a particular commit; Git allows us to do so.
We can reset to a particular commit. To reset it, git reset command can be
used with any option supported by reset command. It will take the default
behavior of a particular command and reset the given commit. The syntax
for resetting commit is given below:

1. $ git reset <option> <commit-sha>

These options can be

o --soft
o --mixed
o --Hard

Git Rm
In Git, the term rm stands for remove. It is used to remove individual files
or a collection of files. The key function of git rm is to remove tracked files
from the Git index. Additionally, it can be used to remove files from both
the working directory and staging index.

The files being removed must be ideal for the branch to remove. No
updates to their contents can be staged in the index. Otherwise, the
removing process can be complex, and sometimes it will not happen. But
it can be done forcefully by -f option.

Let's understand it with an example.

The git rm command


The git rm command is used to remove the files from the working tree and
the index.

If we want to remove the file from our repository. Then it can be done by
the git rm command. Let's take a file say newfile.txt to test the rm
command. The git rm command will be operated as:

1. $ git rm <file Name>

The above command will remove the file from the Git and repository. The
git rm command removes the file not only from the repository but also
from the staging area. If we check the status of the repository, then it will
show as deleted. Consider the below output:
In the above output, the file newfile.txt has been removed from the
version control system. So the repository and the status are shown as
deleted. If we use only the rm command, then it will not permanently
delete the file from the Git. It can be tracked in the staging area. Consider
the below output:

In the above output, the file newfile2.txt has been deleted. But when we
check the status of the repository, we can track the file in the staging
area. It means the newfile2 yet not deleted from the staging area, and it is
also available in the repository. We can get it back on the version control
system by committing it. To commit the file, first, add it to the index and
then commit it. To add this file in the index, run the below command:

1. $ git add newfile2.txt

The above command will add the file to the index. To commit it, run the
below command:

1. $ git commit -m "commit message."

It will commit the file and make it available to the version control system.
Consider the below output:
In the above output, we are retrieving the file from the staging area to our
directory. The newfile2.txt is re-added to our repository.

Git Rm Cached
Sometimes you want to remove files from the Git but keep the files in
your local repository. In other words, you do not want to share your file on
Git. Git allows you to do so. The cached option is used in this case. It
specifies that the removal operation will only act on the staging index, not
on the repository. The git rm command with cached option will be uses as:

1. $ git rm --cached <file name>

The above command will remove a file from the version control system.
The deleted file will remain in the repository. Somehow this command will
act as rm command. Let's understand it with an example.

Suppose we want to remove a file from Git, take newfile1.txt for


operation to remove this file, use the below command:

1. $ git rm --cached newfile1.txt

The above command will delete the file from the version control system,
but still, it can be tracked in the repository. It also can be re-added on the
version control system. To check the file status, use the status command
as:

1. $ git status

Consider the below output:


As we can see from the above output, the newfile1.txt file is deleted from
the version control system, but it can be tracked in the repository. This file
is available on the version control system as an untracked file. We can
track it by committing it.

Undo the Git Rm Command


Execution of git rm command is not permanent; it can be reverted after
execution. These changes cannot be persisted until a new commit is made
on the repository. We can undo the git rm command. There are several
ways to do so. The most usual and straight-forward way is git reset
command. The git reset command will be used as follows:

1. $ git reset HEAD

Or we can also use:

1. $ git reset --hard

The above command will reset the position of the head. So that it will get
the position of its just previous point. Consider the below output:

From the above output, we can see that the file has been successfully
reset to its previous position.
There is another way to undo the git rm command. We can also do it by
git checkout command. A checkout has the same effect and restores the
latest version of a file from HEAD. It will be used as follows:

1. $ git checkout.
Limits of Git Rm command
The git rm is operated only on the current branch. The removing process
is only applied to the working directory and staging index trees. It is not
persisted in the repository history until a new commit is created.

Git Cherry-pick
Cherry-picking in Git stands for applying some commit from one branch
into another branch. In case you made a mistake and committed a change
into the wrong branch, but do not want to merge the whole branch. You
can revert the commit and apply it on another branch.

The main motive of a cherry-pick is to apply the changes introduced by


some existing commit. A cherry-pick looks at a previous commit in the
repository history and update the changes that were part of that last
commit to the current working tree. The definition is straight forward, yet
it is more complicated when someone tries to cherry-pick a commit, or
even cherry-pick from another branch.

Cherry-pick is a useful tool, but always it is not a good option. It can cause
duplicate commits and some other scenarios where other merges are
preferred instead of cherry-picking. It is a useful tool for a few situations.
It is in contrast with different ways such as merge and rebase command.
Merge and rebase can usually apply many commits in another branch.

Why Cherry-Pick
Suppose you are working with a team of developers on a medium to large-
sized project. Some changes proposed by another team member and you
want to apply some of them to your main project, not all. Since managing
the changes between several Git branches can become a complex task,
and you don't want to merge a whole branch into another branch. You
only need to pick one or two specific commits. To pick some changes into
your main project branch from other branches is called cherry-picking.

Some scenarios in which you can cherry-pick:

Scenerio1: Accidently make a commit in a wrong branch.

Git cherry-pick is helpful to apply the changes that are accidentally made
in the wrong branch. Suppose I want to make a commit in the master
branch, but by mistake, we made it in any other branch. See the below
commit.

In the above example, I want to make a commit for the master branch,
but accidentally I made it in the new branch. To make all the changes of
the new branch into the master branch, we will use the git pull, but for
this particular commit, we will use git cherry-pick command. See the
below output:
In the given output, I have used the git log command to check the commit
history. Copy the particular commit id that you want to make on the
master branch. Now switch to master branch and cherry-pick it there. See
the below output:

Syntax:

1. $ git cherry-pick <commit id>

Output:

From the given output, you can see that I have pasted the commit id with
git cherry-pick command and made that commit into my master branch.
You can check it by git log command.
Scenario2: Made the changes proposes by another team member.

Another use of cherry-picking is to make the changes proposed by


another team member. Suppose one of my team members made any
changes in the main project and suggests it for the main project. You can
cheery-pick it after review.

Usage of cherry-pick
o It is a handy tool for team collaboration.
o It is necessary in case of bug fixing because bugs are fixed and tested in
the development branch with their commits.
o It is mostly used in undoing changes and restoring lost commits.
o You can avoid useless conflicts by using git cherry-pick instead of other
options.
o It is a useful tool when a full branch merge is not possible due to
incompatible versions in the various branches.
o The git cherry-pick is used to access the changes introduced to a sub-
branch, without changing the branch.

Git log
The advantage of a version control system is that it records changes.
These records allow us to retrieve the data like commits, figuring out
bugs, updates. But, all of this history will be useless if we cannot navigate
it. At this point, we need the git log command.

Git log is a utility tool to review and read a history of everything that
happens to a repository. Multiple options can be used with a git log to
make history more specific.

Generally, the git log is a record of commits. A git log contains the
following data:

o A commit hash, which is a 40 character checksum data generated by


SHA (Secure Hash Algorithm) algorithm. It is a unique number.
o Commit Author metadata: The information of authors such as author
name and email.
o Commit Date metadata: It's a date timestamp for the time of the
commit.
o Commit title/message: It is the overview of the commit given in the
commit message.

How to Exit the git log Command?


There may be a situation that occurs, you run the git log command, and
you stuck there. You want to type or back to bash, but you can't. When
you click the Enter key, it will navigate you to the older command until
the end flag.

The solution to this problem is to press the q (Q for quit). It will quit you
from the situation and back you to the command line. Now, you can
perform any of the commands.

Basic Git log


Git log command is one of the most usual commands of git. It is the most
useful command for Git. Every time you need to check the history, you
have to use the git log command. The basic git log command will display
the most recent commits and the status of the head. It will use as:

1. $ git log

The above command will display the last commits. Consider the below
output:
The above command is listing all the recent commits. Each commit
contains some unique sha-id, which is generated by the SHA algorithm. It
also includes the date, time, author, and some additional details.

We can perform some action like scrolling, jumping, move, and quit on the
command line. To scroll on the command line press k for moving up, j for
moving down, the spacebar for scrolling down by a full page to scroll up
by a page and q to quit from the command line.

<

Git Log Oneline


The oneline option is used to display the output as one commit per line. It
also shows the output in brief like the first seven characters of the commit
SHA and the commit message.
It will be used as follows:

1. $ git log --oneline

So, usually we can say that the --oneline flag causes git log to display:

o one commit per line


o the first seven characters of the SHA
o the commit message

Consider the below output:

As we can see more precisely from the above output, every commit is
given only in one line with a seven-digit sha number and commit
message.

Git Log Stat


The log command displays the files that have been modified. It also shows
the number of lines and a summary line of the total records that have
been updated.

Generally, we can say that the stat option is used to display

o the modified files,


o The number of lines that have been added or removed
o A summary line of the total number of records changed
o The lines that have been added or removed.

It will be used as follows:


1. $ git log --stat

The above command will display the files that have been modified.
Consider the below output:

From the above output, we can see that all listed commits are
modifications in the repository.

Git log P or Patch


The git log patch command displays the files that have been modified. It
also shows the location of the added, removed, and updated lines.

It will be used as:

1. $ git log --patch

Or

1. $ git log -p
Generally, we can say that the --patch flag is used to display:

o Modified files
o The location of the lines that you added or removed
o Specific changes that have been made.

Consider the below output:

The above output is displaying the modified files with the location of lines
that have been added or removed.

Git Log Graph


Git log command allows viewing your git log as a graph. To list the
commits in the form of a graph, run the git log command with --graph
option. It will run as follows:
1. $ git log --graph

To make the output more specific, you can combine this command with --
oneline option. It will operate as follows:

1. $ git log --graph --oneline


Filtering the Commit History
We can filter the output according to our needs. It's a unique feature of
Git. We can apply many filters like amount, date, author, and more on
output. Each filter has its specifications. They can be used for
implementing some navigation operations on output.

Let's understand each of these filters in detail.

By Amount:

We can limit the number of output commit by using git log command. It is
the most specific command. This command will remove the complexity if
you are interested in fewer commits.

To limit the git log's output, including the -<n> option. If we want only the
last three commit, then we can pass the argument -3 in the git log
command. Consider the below output:

As we can see from the above output, we can limit the output of git log.

By Date and Time:


We can filter the output by date and time. We have to pass --after or -
before argument to specify the date. These both argument accept a
variety of date formats. It will run as follows:

1. $ git log --after="yy-mm-dd"

The above command will display all the commits made after the given
date. Consider the below output:

The above command is listing all the commits after "2019-11-01".

We can also pass the applicable reference statement like "yesterday," "1
week ago", "21 days ago," and more. It will run as:

1. git log --after="21 days ago"

The above command will display the commits which have been made 21
days ago. Consider the below output:

We can also track the commits between two dates. To track the commits
that were created between two dates, pass a statement reference --
before and --after the date. Suppose, we want to track the commits
between "2019-11-01" and "2019-11-08". We will run the command as
follows:

1. $ git log --after="2019-11-01" --before="2019-11-08 "

The above command will display the commits made between the dates.
Consider the below output:
The above output is displaying the commits between the given period. We
can use --since and --until instead of --after and --before. Because they are
synonyms, respectively.

By Author:

We can filter the commits by a particular user. Suppose, we want to list


the commits only made by a particular team member. We can use -author
flag to filter the commits by author name. This command takes a regular
expression and returns the list of commits made by authors that match
that pattern. You can use the exact name instead of the pattern. This
command will run as follows:

1. $ git log --author="Author name"

The above command will display all the commits made by the given
author. Consider the below output:
From the above output, we can see that all the commits by the
author ImDwivedi1 are listed.

We can use a string instead of a regular expression or exact name.


Consider the below statement:

1. $ git log --author="Stephen"

The above statement will display all commits whose author includes the
name, Stephen. The author's name doesn't need to be an exact match; it
just has the specified phrase.

As we know, the author's email is also involved with the author's name, so
that we can use the author's email as the pattern or exact search.
Suppose, we want to track the commits by the authors whose email
service is google. To do so, we can use wild cards as "@gmail.com."
Consider the below statement:

1. $ git log -author="@gmail.com"

The above command will display the commits by authors as given in the
pattern. Consider the below output:

By Commit message:
To filter the commits by the commit message. We can use the grep
option, and it will work as the author option.

It will run as follows:

1. $ git log --grep=" Commit message."

We can use the short form of commit message instead of a complete


message. Consider the below output.

The above output is displaying all the commits that contain the word
commit in its commit message.

There are many other filtering options available like we can filter by file
name, content, and more.
Git Diff
Git diff is a command-line utility. It's a multiuse Git command. When it is
executed, it runs a diff function on Git data sources. These data sources
can be files, branches, commits, and more. It is used to show changes
between commits, commit, and working tree, etc.

It compares the different versions of data sources. The version control


system stands for working with a modified version of files. So, the diff
command is a useful tool for working with Git.

However, we can also track the changes with the help of git log command
with option -p. The git log command will also work as a git diff command.

Let's understand different scenarios where we can utilize the git diff
command.

Scenerio1: Track the changes that have not been staged.

The usual use of git diff command that we can track the changes that
have not been staged.

Suppose we have edited the newfile1.txt file. Now, we want to track what
changes are not staged yet. Then we can do so from the git diff command.
Consider the below output:

From the above output, we can see that the changes made on newfile1.txt
are displayed by git diff command. As we have edited it as "changes are
made to understand the git diff command." So, the output is displaying
the changes with its content. The highlighted section of the above output
is the changes in the updated file. Now, we can decide whether we want
to stage this file like this or not by previewing the changes.

Scenerio2: Track the changes that have staged but not committed:

The git diff command allows us to track the changes that are staged but
not committed. We can track the changes in the staging area. To check
the already staged changes, use the --staged option along with git diff
command.

To check the untracked file, run the git status command as:

1. $ git status

The above command will display the untracked file from the repository.
Now, we will add it to the staging area. To add the file in the staging area,
run the git add command as:

1. $ git add < file name>

The above command will add the file in the staging area. Consider the
below output:

Now, the file is added to the staging area, but it is not committed yet. So,
we can track the changes in the staging area also. To check the staged
changes, run the git diff command along with --staged option. It will be
used as:

1. $ git diff --staged

The above command will display the changes of already staged files.
Consider the below output:
The given output is displaying the changes of newfile1.txt, which is
already staged.

Scenerio3: Track the changes after committing a file:

Git, let us track the changes after committing a file. Suppose we have
committed a file for the repository and made some additional changes
after the commit. So we can track the file on this stage also.

In the below output, we have committed the changes that we made on


our newfile1.txt. Consider the below output:

Now, we have changed the newfile.txt file again as "Changes are made
after committing the file." To track the changes of this file, run the git diff
command with HEAD argument. It will run as follows:

1. $ git diff HEAD

The above command will display the changes in the terminal. Consider the
below output:
The above command is displaying the updates of the file newfile1.txt on
the highlighted section.

Scenario4: Track the changes between two commits:

We can track the changes between two different commits. Git allows us to
track changes between two commits, whether it is the latest commit or
the old commit. But the required thing for this is that we must have a list
of commits so that we can compare. The usual command to list the
commits in the git log command. To display the recent commits, we can
run the command as:

1. $ git log

The above command will list the recent commits.

Suppose, we want to track changes of a specified from an earlier commit.


To do so, we must need the commits of that specified file. To display the
commits of any specified, run the git log command as:

1. $ git log -p --follow -- filename

The above command will display all the commits of a specified file.
Consider the below output:
The above output is displaying all the commits of newfile1.txt. Suppose
we want to track the changes between
commits e553fc08cb and f1ddc7c9e7. The git diff command lets track
the changes between two commits. It will be commanded as:

1. $ git diff <commit1-sha> <commit2-sha>

The above command will display the changes between two commits.
Consider the below output:
The above output is displaying all the changes made
on newfile1.txt from commit e553fc08cb (most recent) to
commit f1ddc7c9e7 (previous).

Git Diff Branches


Git allows comparing the branches. If you are a master in branching, then
you can understand the importance of analyzing the branches before
merging. Many conflicts can arise if you merge the branch without
comparing it. So to avoid these conflicts, Git allows many handy
commands to preview, compare, and edit the changes.

We can track changes of the branch with the git status command, but few
more commands can explain it in detail. The git diff command is a widely
used tool to track the changes.

The git diff command allows us to compare different versions of branches


and repository. To get the difference between branches, run the git diff
command as follows:

1. $ git diff <branch 1> < branch 2>

The above command will display the differences between branch 1 and
branch 2. So that you can decide whether you want to merge the branch
or not. Consider the below output:
The above output is displaying the differences between my repository
branches test and test2. The git diff command is giving a preview of both
branches. So, it will be helpful to perform any operation on branches.
Git Status
The git status command is used to display the state of the repository and
staging area. It allows us to see the tracked, untracked files and changes.
This command will not show any commit records or information.

Mostly, it is used to display the state between Git Add and Git
commit command. We can check whether the changes and files are
tracked or not.

Let's understand the different states of status command.

Status when Working Tree is cleaned


Before starting with git status command, let's see how the git status looks
like when there are no changes made. To check the status, open the git
bash, and run the status command on your desired directory. It will run as
follows:

1. $ git status

Output:

Since there is nothing to track or untrack in the working tree, so the


output is showing as the working tree is clean.

Status when a new file is created


When we create a file in the repository, the state of the repository
changes. Let's create a file using the touch command. Now, check the
status using the status command. Consider the below output:
As we can see from the above output, the status is showing as "nothing
added to commit but untracked files present (use "git add" to
track)". The status command also displays the suggestions. As in the
above output, it is suggesting to use the add command to track the file.

Let's track the file and will see the status after adding a file to the
repository. To track the file, run the add command. Consider the below
output:

From the above output, we can see that the status after staging the file is
showing as "changes to be committed".

Before committing blindly, we can check the status. This command will
help us to avoid the changes that we don't want to commit. Let's commit
it and then check the status. Consider the below output:

We can see that the current status after committing the file is clean as it
was before.

Status when an existing file is modified


Let's check the status when an existing file is modified. To modify file, run
the echo command as follows:
1. $ echo "Text"> Filename

The above command will add the text to the specified file, now check the
status of the repository. Consider the below output:

We can see that the updated file is displayed as untracked files. It is


shown in red color because it is not staged yet. When it will stage, its color
will change to Green. Consider the below output:

Status when a file is deleted


Let's check the status when a file is deleted from the repository. To delete
a file from the repository, run the rm command as follows:

1. $ git rm < File Name>

The above command will delete the specified file from the repository.
Now, check the status of the repository. Consider the below output:

The current status of the repository has been updated as deleted


The git branch <branch name> command creates a new branch in your local
repository. It does not create a branch on the remote repository; instead, it creates a new
branch based on your current commit.

To create a branch on the remote repository, typically on a service like GitHub or GitLab,
you would need to push your local branch to the remote repository after creating it locally.

Here's the typical workflow to create and push a branch to the remote repository:

1. Create a local branch:


phpCopy code
git branch <branch name>
2. Switch to the newly created branch:
phpCopy code
git checkout <branch name>
Alternatively, you can use a single command to create and switch to the new branch:
cssCopy code
git checkout - b <branch name>
3. Make changes, commit, and push to the remote repository:
sqlCopy code
git add . git commit - m "Your commit message" git push origin < branch
name >

This sequence of commands creates a new branch locally, switches to it, makes changes,
commits those changes, and then pushes the branch to the remote repository. After pushing
the branch, it will be available on the remote repository for others to see and work with.

Git Branch
A branch is a version of the repository that diverges from the main
working project. It is a feature available in most modern version control
systems. A Git project can have more than one branch. These branches
are a pointer to a snapshot of your changes. When you want to add a new
feature or fix a bug, you spawn a new branch to summarize your changes.
So, it is complex to merge the unstable code with the main code base and
also facilitates you to clean up your future history before merging with the
main branch.
Git Master Branch
The master branch is a default branch in Git. It is instantiated when first
commit made on the project. When you make the first commit, you're
given a master branch to the starting commit point. When you start
making a commit, then master branch pointer automatically moves
forward. A repository can have only one master branch.

Master branch is the branch in which all the changes eventually get
merged back. It can be called as an official working version of your
project.

Operations on Branches
We can perform various operations on Git branches. The git branch
command allows you to create, list, rename and delete branches.
Many operations on branches are applied by git checkout and git merge
command. So, the git branch is tightly integrated with the git
checkout and git merge commands.

The Operations that can be performed on a branch:

Create Branch
You can create a new branch with the help of the git branch command.
This command will be used as:

Syntax:

1. $ git branch <branch name>


Output:

This command will create the branch B1 locally in Git directory.

List Branch
You can List all of the available branches in your repository by using the
following command.

Either we can use git branch - list or git branch command to list the
available branches in the repository.

Syntax:

1. $ git branch --list

or

1. $ git branch

Output:

Here, both commands are listing the available branches in the repository.
The symbol * is representing currently active branch.

Delete Branch
You can delete the specified branch. It is a safe operation. In this
command, Git prevents you from deleting the branch if it has unmerged
changes. Below is the command to do this.

Syntax:
1. $ git branch -d<branch name>

Output:

This command will delete the existing branch B1 from the repository.

The git branch d command can be used in two formats. Another format
of this command is git branch D. The 'git branch D' command is used
to delete the specified branch.

1. $ git branch -D <branch name>


Delete a Remote Branch
You can delete a remote branch from Git desktop application. Below
command is used to delete a remote branch:

Syntax:

1. $ git push origin -delete <branch name>

Output:

As you can see in the above output, the remote branch


named branch2 from my GitHub account is deleted.

Switch Branch
Git allows you to switch between the branches without making a commit.
You can switch between two branches with the git checkout command.
To switch between the branches, below command is used:

1. $ git checkout<branch name>

Switch from master Branch


You can switch from master to any other branch available on your
repository without making any commit.

Syntax:

1. $ git checkout <branch name>

Output:

As you can see in the output, branches are switched


from master to branch4 without making any commit.

Switch to master branch

You can switch to the master branch from any other branch with the help
of below command.

Syntax:

1. $ git branch -m master

Output:

As you can see in the above output, branches are switched from branch1
to master without making any commit.

Rename Branch
We can rename the branch with the help of the git branch command. To
rename a branch, use the below command:

Syntax:

1. $ git branch -m <old branch name><new branch name>

Output:
As you can see in the above output, branch4 renamed as renamedB1.

Merge Branch
Git allows you to merge the other branch with the currently active branch.
You can merge two branches with the help of git merge command. Below
command is used to merge the branches:

Syntax:

1. $ git merge <branch name>

Output:

From the above output, you can see that the


master branch merged with renamedB1. Since I have made no-commit
before merging, so the output is showing as already up to date.

Git Merge and Merge Conflict


In Git, the merging is a procedure to connect the forked history. It joins
two or more development history together. The git merge command
facilitates you to take the data created by git branch and integrate them
into a single branch. Git merge will associate a series of commits into one
unified history. Generally, git merge is used to combine two branches.

It is used to maintain distinct lines of development; at some stage, you


want to merge the changes in one branch. It is essential to understand
how merging works in Git.

In the above figure, there are two branches master and feature. We can
see that we made some commits in both functionality and master branch,
and merge them. It works as a pointer. It will find a common base commit
between branches. Once Git finds a shared base commit, it will create a
new "merge commit." It combines the changes of each queued merge
commit sequence.

The "git merge" command


The git merge command is used to merge the branches.

The syntax for the git merge command is as:

1. $ git merge <query>

It can be used in various context. Some are as follows:

Scenario1: To merge the specified commit to currently active


branch:

Use the below command to merge the specified commit to currently


active branch.

1. $ git merge <commit>

The above command will merge the specified commit to the currently
active branch. You can also merge the specified commit to a specified
branch by passing in the branch name in <commit>. Let's see how to
commit to a currently active branch.

See the below example. I have made some changes in my project's


file newfile1.txt and committed it in my test branch.

Copy the particular commit you want to merge on an active branch and
perform the merge operation. See the below output:

In the above output, we have merged the previous commit in the active
branch test2.

Scenario2: To merge commits into the master branch:

To merge a specified commit into master, first discover its commit id. Use
the log command to find the particular commit id.

1. $git log

See the below output:


To merge the commits into the master branch, switch over to the master
branch.

1. $ git checkout master

Now, Switch to branch 'master' to perform merging operation on a


commit. Use the git merge command along with master branch name. The
syntax for this is as follows:

1. $ git merge master

See the below output:

As shown in the above output, the commit for the commit


id 2852e020909dfe705707695fd6d715cd723f9540 has merged into
the master branch. Two files have changed in master branch. However,
we have made this commit in the test branch. So, it is possible to merge
any commit in any of the branches.

Open new files, and you will notice that the new line that we have
committed to the test branch is now copied on the master branch.
Scenario 3: Git merge branch.

Git allows merging the whole branch in another branch. Suppose you have
made many changes on a branch and want to merge all of that at a time.
Git allows you to do so. See the below example:

In the given output, I have made changes in newfile1 on the test branch.
Now, I have committed this change in the test branch.

Now, switch to the desired branch you want to merge. In the given
example, I have switched to the master branch. Perform the below
command to merge the whole branch in the active branch.

1. $ git merge <branchname>

As you can see from the given output, the whole commits of branch test2
have merged to branch master.

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.
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:
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:
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:

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>.
Resolve Conflict:
To resolve the conflict, it is necessary to know whether the conflict occurs
and why it occurs. Git merge tool command is used to resolve the conflict.
The merge command is used as follows:

1. $ git mergetool

In my repository, it will result in:

The above output shows the status of the conflicted file. To resolve the
conflict, enter in the insert mode by merely pressing I key and make
changes as you want. Press the Esc key, to come out from insert mode.
Type the: w! at the bottom of the editor to save and exit the changes. To
accept the changes, use the rebase command. It will be used as follows:

1. $ git rebase --continue

Hence, the conflict has resolved. See the below output:


In the above output, the conflict has resolved, and the local repository is
synchronized with a remote repository.

To see that which is the first edited text of the merge conflict in your file,
search the file attached with conflict marker <<<<<<<. You can see the
changes from the HEAD or base branch after the line <<<<<<<
HEAD in your text editor. Next, you can see the divider like =======. It
divides your changes from the changes in the other branch, followed by
>>>>>>> BRANCH-NAME. In the above example, user1 wrote "<h1>
Git is a version control</h1>" in the base or HEAD branch and user2
wrote "<h2> Git is a version control</h2>".

Decide whether you want to keep only your branch's changes or the other
branch's changes, or create a new change. Delete the conflict
markers <<<<<<<, =======, >>>>>>> and create final changes
you want to merge.
Git Rebase
Rebasing is a process to reapply commits on top of another base trip. It is
used to apply a sequence of commits from distinct branches into a final
commit. It is an alternative of git merge command. It is a linear process of
merging.

In Git, the term rebase is referred to as the process of moving or


combining a sequence of commits to a new base commit. Rebasing is very
beneficial and it visualized the process in the environment of a feature
branching workflow.

It is good to rebase your branch before merging it.

Generally, it is an alternative of git merge command. Merge is always a


forward changing record. Comparatively, rebase is a compelling history
rewriting tool in git. It merges the different commits one by one.

Suppose you have made three commits in your master branch and three
in your other branch named test. If you merge this, then it will merge all
commits in a time. But if you rebase it, then it will be merged in a linear
manner. Consider the below image:
The above image describes how git rebase works. The three commits of
the master branch are merged linearly with the commits of the test
branch.

Merging is the most straightforward way to integrate the branches. It


performs a three-way merge between the two latest branch commits.

How to Rebase
When you made some commits on a feature branch (test branch) and
some in the master branch. You can rebase any of these branches. Use
the git log command to track the changes (commit history). Checkout to
the desired branch you want to rebase. Now perform the rebase command
as follows:

Syntax:

1. $git rebase <branch name>

If there are some conflicts in the branch, resolve them, and perform below
commands to continue changes:

1. $ git status

It is used to check the status,

1. $git rebase --continue

The above command is used to continue with the changes you made. If
you want to skip the change, you can skip as follows:

1. $ git rebase --skip

When the rebasing is completed. Push the repository to the origin.


Consider the below example to understand the git merge command.
Suppose that you have a branch say test2 on which you are working. You
are now on the test2 branch and made some changes in the project's
file newfile1.txt.

Add this file to repository:

1. $ git add newfile1.txt

Now, commit the changes. Use the below command:

1. $ git commit -m "new commit for test2 branch."

The output will look like:

[test2 a835504] new commitfor test2 branch


1 file changed, 1 insertion(+)

Switch the branch to master:

1. $ git checkout master

Output:

Switched to branch 'master.'


Your branch is up to date with 'origin/master.'

Now you are on the master branch. I have added the changes to my file,
says newfile.txt. The below command is used to add the file in the
repository.

1. $ git add newfile.txt

Now commit the file for changes:

1. $ git commit -m " new commit made on the master branch."

Output:

[master 7fe5e7a] new commit made on master


1 file changed, 1 insertion(+)
HiMaNshU@HiMaNshU-PC MINGW64 ~/Desktop/GitExample2 (master)

To check the log history, perform the below command.

1. $ git log --oneline

Output:
As we can see in the log history, there is a new commit in the master
branch. If I want to rebase my test2 branch, what should I do? See the
below rebase branch scenario:

Rebase Branch
If we have many commits from distinct branches and want to merge it in
one. To do so, we have two choices either we can merge it or rebase it. It
is good to rebase your branch.

From the above example, we have committed to the master branch and
want to rebase it on the test2 branch. Let's see the below commands:

1. $ git checkout test2

This command will switch you on the test2 branch from the master.

Output:

Switched to branch 'test2.'

Now you are on the test2 branch. Hence, you can rebase the test2 branch
with the master branch. See the below command:

1. $ git rebase master

This command will rebase the test2 branch and will show as Applying:
new commit on test2 branch. Consider the below output:

Output:
Git Interactive Rebase
Git facilitates with Interactive Rebase; it is a potent tool that allows
various operations like edit, rewrite, reorder, and more on existing
commits. Interactive Rebase can only be operated on the currently
checked out branch. Therefore, set your local HEAD branch at the sidebar.

Git interactive rebase can be invoked with rebase command, just type -
i along with rebase command. Here 'i' stands for interactive. Syntax of
this command is given below:

Syntax:

1. $ git rebase -i

It will list all the available interactive options.

Output:

After the given output, it will open an editor with available options.
Consider the below output:

Output:
When we perform the git interactive rebase command, it will open your
default text editor with the above output.

The options it contains are listed below:

o Pick
o Reword
o Edit
o Squash
o Fixup
o Exec
o Break
o Drop
o Label
o Reset
o Merge

The above options perform their specific tasks with git-rebase. Let's
understand each of these options in brief.
Pick (-p):

Pick stands here that the commit is included. Order of the commits
depends upon the order of the pick commands during rebase. If you do
not want to add a commit, you have to delete the entire line.

Reword (-r):

The reword is quite similar to pick command. The reword option paused
the rebase process and provides a chance to alter the commit message. It
does not affect any changes made by the commit.

Edit (-e):

The edit option allows for amending the commit. The amending means,
commits can be added or changed entirely. We can also make additional
commits before rebase continue command. It allows us to split a large
commit into the smaller commit; moreover, we can remove erroneous
changes made in a commit.

Squash (-s):

The squash option allows you to combine two or more commits into a
single commit. It also allows us to write a new commit message for
describing the changes.

Fixup (-f):

It is quite similar to the squash command. It discarded the message of the


commit to be merged. The older commit message is used to describe both
changes.

Exec (-x):

The exec option allows you to run arbitrary shell commands against a
commit.

Break (-b):

The break option stops the rebasing at just position. It will continue
rebasing later with 'git rebase --continue' command.

Drop (-d):

The drop option is used to remove the commit.

Label (-l):

The label option is used to mark the current head position with a name.
Reset (-t):

The reset option is used to reset head to a label.

GitMerge vs. Rebase


It is a most common puzzling question for the git user's that when to use
merge command and when to use rebase. Both commands are similar,
and both are used to merge the commits made by the different branches
of a repository.

Rebasing is not recommended in a shared branch because the rebasing


process will create inconsistent repositories. For individuals, rebasing can
be more useful than merging. If you want to see the complete history, you
should use the merge. Merge tracks the entire history of commits, while
rebase rewrites a new one.

Git rebase commands said as an alternative of git merge. However, they


have some key differences:

Git Merge Git Rebase

Merging creates a final commit at merging. Git rebase does not create
any commit at rebasing.

It merges all commits as a single commit. It creates a linear track of


commits.

It creates a graphical history that might be a bit complex It creates a linear history
to understand. that can be easily
understood.

It is safe to merge two branches. Git "rebase" deals with the


severe operation.

Merging can be performed on both public and private It is the wrong choice to
branches. use rebasing on public
branches.

Merging integrates the content of the feature branch with Rebasing of the master
the master branch. So, the master branch is changed, and branch may affect the
feature branch history remains consistence. feature branch.

Merging preserves history. Rebasing rewrites history.


Git merge presents all conflicts at once. Git rebase presents
conflicts one by one.

Git Squash
In Git, the term squash is used to squash the previous commits into one. It
is not a command; instead, it is a keyword. The squash is an excellent
technique for group-specific changes before forwarding them to others.
You can merge several commits into a single commit with the compelling
interactive rebase command.

If you are a Git user, then you must have realized the importance of
squashing a commit. Especially if you are an open-source contributor,
then many times, you have to create a PR (pull request) with squashed
commit. You can also squash commits if you have already created a PR.

Let's understand how to squash commits?

Git Squash Commits


Being a responsible contributor to Git, it is necessary to make the
collaboration process efficient and meaningful. Git allows some powerful
collaboration tools in different ways. Git squash is one of the powerful
tools that facilitate efficient and less painful collaboration.

The squash is not any command; instead, it's one of many options
available to you under git interactive rebases. The squash allows us to
rewrite history. Suppose we have made many commits during the project
work, squashing all the commits into a large commit is the right choice
than pushing. Let's understand how to squash two commits.

Step1: Check the commit history

To check the commit history, run the below command:

1. $ git log --oneline


The given command will display the history in one line. We can track the
history and choose the commits we want to squash. Consider the below
output:

Step 2: Choose the commits to squash.

Suppose we want to squash the last commits. To squash commits, run the
below command:

1. $ git rebase -i HEAD ~3

The above command will open your default text editor and will squash the
last three commits. The editor will open as follows:
From the above image, we can see previous commits shown at the top of
the editor. If we want to merge them into a single commit, then we have
to replace the word pick with the squash on the top of the editor. To
write on the editor, press 'i' button to enter in insert mode. After editing
the document, press the :wq to save and exit from the editor.

Step 3: update the commits

On pressing enter key, a new window of the text editor will be opened to
confirm the commit. We can edit the commit message on this screen.

I am editing my first commit message because it will be a combination of


all three commits. Consider the below image:
The above image is the editor screen to confirm the merging of commits.
Here we can update the commit messages. To edit on this editor, press
the 'i' button for insert mode and edit the desired text. Press
the :wq keys, to save and exit from the editor.

When we exit the editor, it will show the description of updates. Consider
the below output:

The above output is listing the description of changes that have been
made on the repository. Now, the commits have been squashed. Check
the commit history for confirmation with the help of the git log. Consider
the below output:
Step 4: Push the squashed commit

Now, we can push this squashed commit on the remote server. To push
this squashed commit, run the below command:

1. $ git push origin master

Or

1. $ git push -f origin master

The above command will push the changes on the remote server. We can
check this commit on our remote repository. Consider the below image:
As you can see from the above image. A new commit has been added to
my remote repository.

Drawbacks of Squashing
There are no significant drawbacks of squashing. But we can consider
some facts that may affect the project. These facts are as follows:

The squashing commits, and rebasing changes the history of the


repository. If any contributor does not pay attention to the updated
history, then it may create conflict. I suggest a clean history because it is
more valuable than another one. Although we can check the original
history in the ref log.

There is another drawback, we may lose granularity because of


squashing. Try to make minimum squashes while working with Git. So, if
you are new on Git, then try to stay away from squash.

Git Fetch
Git "fetch" Downloads commits, objects and refs from another repository.
It fetches branches and tags from one or more repositories. It holds
repositories along with the objects that are necessary to complete their
histories to keep updated remote-tracking branches.
The "git fetch"command
The "git fetch" command is used to pull the updates from remote-
tracking branches. Additionally, we can get the updates that have been
pushed to our remote branches to our local machines. As we know, a
branch is a variation of our repositories main code, so the remote-tracking
branches are branches that have been set up to pull and push from
remote repository.

How to fetch Git Repository


We can use fetch command with many arguments for a particular data
fetch. See the below scenarios to understand the uses of fetch command.

Scenario 1: To fetch the remote repository:


We can fetch the complete repository with the help of fetch command
from a repository URL like a pull command does. See the below output:

Syntax:

1. $ git fetch< repository Url>

Output:
In the above output, the complete repository has fetched from a remote
URL.

Scenario 2: To fetch a specific branch:


We can fetch a specific branch from a repository. It will only access the
element from a specific branch. See the below output:

Syntax:

1. $ git fetch <branch URL><branch name>

Output:

In the given output, the specific branch test has fetched from a remote
URL.

Scenario 3: To fetch all the branches simultaneously:


The git fetch command allows to fetch all branches simultaneously from a
remote repository. See the below example:

Syntax:
1. $ git fetch -all

Output:

In the above output, all the branches have fetched from the repository
Git-Example.

Scenario 4: To synchronize the local repository:


Suppose, your team member has added some new features to your
remote repository. So, to add these updates to your local repository, use
the git fetch command. It is used as follows.

Syntax:

1. $ git fetch origin

Output:

In the above output, new features of the remote repository have updated
to my local system. In this output, the branch test2 and its objects are
added to the local repository.

The git fetch can fetch from either a single named repository or URL or
from several repositories at once. It can be considered as the safe version
of the git pull commands.
The git fetch downloads the remote content but not update your local
repo's working state. When no remote server is specified, by default, it will
fetch the origin remote.

Differences between git fetch and git pull


To understand the differences between fetch and pull, let's know the
similarities between both of these commands. Both commands are used
to download the data from a remote repository. But both of these
commands work differently. Like when you do a git pull, it gets all the
changes from the remote or central repository and makes it available to
your corresponding branch in your local repository. When you do a git
fetch, it fetches all the changes from the remote repository and stores it in
a separate branch in your local repository. You can reflect those changes
in your corresponding branches by merging.

So basically,

1. git pull = git fetch + git merge


Git Fetch vs. Pull
Some of the key differences between both of these commands are as
follows:

git fetch git pull

Fetch downloads only new data from a Pull is used to update your current HEAD
remote repository. branch with the latest changes from the
remote server.

Fetch is used to get a new view of all the Pull downloads new data and directly
things that happened in a remote integrates it into your current working copy
repository. files.

Fetch never manipulates or spoils data. Pull downloads the data and integrates it
with the current working file.

It protects your code from merge In git pull, there are more chances to create
conflict. the merge conflict.

It is better to use git fetch command It is not an excellent choice to use git pull if
with git merge command on a pulled you already pulled any repository.
repository.
Git Pull / Pull Request
The term pull is used to receive data from GitHub. It fetches and merges
changes from the remote server to your working directory. The git pull
command is used to pull a repository.

Pull request is a process for a developer to notify team members that they
have completed a feature. Once their feature branch is ready, the
developer files a pull request via their remote server account. Pull request
announces all the team members that they need to review the code and
merge it into the master branch.

The below figure demonstrates how pull acts between different locations
and how it is similar or dissimilar to other related commands.
The "git pull" command
The pull command is used to access the changes (commits)from a remote
repository to the local repository. It updates the local branches with the
remote-tracking branches. Remote tracking branches are branches that
have been set up to push and pull from the remote repository. Generally,
it is a collection of the fetch and merges command. First, it fetches the
changes from remote and combined them with the local repository.

The syntax of the git pull command is given below:

Syntax:

1. $ git pull <option> [<repository URL><refspec>...]

In which:

<option>: Options are the commands; these commands are used as an


additional option in a particular command. Options can be -q (quiet), -
v (verbose), -e(edit) and more.

<repository URL>: Repository URL is your remote repository's URL


where you have stored your original repositories like GitHub or any other
git service. This URL looks like:

1. https://github.com/ImDwivedi1/GitExample2.git

To access this URL, go to your account on GitHub and select the


repository you want to clone. After that, click on
the clone or download option from the repository menu. A new pop up
window will open, select clone with https option from available options.
See the below screenshot:

Copy the highlighted URL. This URL is used to Clone the repository.
<Refspec>: A ref is referred to commit, for example, head (branches),
tags, and remote branches. You can check head, tags, and remote
repository in .git/ref directory on your local repository. Refspec specifies
and updates the refs.

How to use pull:

It is essential to understand how it works and how to use it. Let's take an
example to understand how it works and how to use it. Suppose I have
added a new file say design2.css in my remote repository of project
GitExample2.

To create the file first, go to create a file option given on repository sub-
functions. After that, select the file name and edit the file as you want.
Consider the below image.

Go to the bottom of the page, select a commit message and description of


the file. Select whether you want to create a new branch or commit it
directly in the master branch. Consider the below image:
Now, we have successfully committed the changes.

To pull these changes in your local repository, perform the git pull
operation on your cloned repository. There are many specific options
available for pull command. Let's have a look at some of its usage.

Default git pull:


We can pull a remote repository by just using the git pull command. It's a
default option. Syntax of git pull is given below:

Syntax:

1. $ git pull

Output:

In the given output, the newly updated objects of the repository are
fetched through the git pull command. It is the default version of the git
pull command. It will update the newly created file design2.css file and
related object in the local repository. See the below image.
As you can see in the above output, the design2.css file is added to the
local repository. The git pull command is equivalent to git fetch origin
head and git merge head. The head is referred to as the ref of the
current branch.

Git Pull Remote Branch


Git allows fetching a particular branch. Fetching a remote branch is a
similar process, as mentioned above, in git pull command. The only
difference is we have to copy the URL of the particular branch we want to
pull. To do so, we will select a specific branch. See the below image:

In the above screenshot, I have chosen my branch named edited to copy


the URL of the edited branch. Now, I am going to pull the data from the
edited branch. Below command is used to pull a remote branch:

Syntax:

1. $ git pull <remote branch URL>

Output:
In the above output, the remote branch edited has copied.

Git Force Pull


Git force pull allows for pulling your repository at any cost. Suppose the
below scenario:

If you have updated any file locally and other team members updated it
on the remote. So, when will you fetch the repository, it may create a
conflict.

We can say force pull is used for overwriting the files. If we want to
discard all the changes in the local repository, then we can overwrite it by
influentially pulling it. Consider the below process to force pull a
repository:

Step1: Use the git fetch command to download the latest updates from
the remote without merging or rebasing.

1. $ git fetch -all

Step2: Use the git reset command to reset the master branch with
updates that you fetched from remote. The hard option is used to
forcefully change all the files in the local repository with a remote
repository.

1. $ git reset -hard <remote>/<branch_name>


2. $ git reset-hard master

Consider the below output:


In the above output, I have updated my design2.css file and forcefully pull
it into the repository.

Git Pull Origin Master


There is another way to pull the repository. We can pull the repository by
using the git pull command. The syntax is given below:

1. $ git pull <options><remote>/<branchname>


2. $ git pull origin master

In the above syntax, the term origin stands for the repository location
where the remote repository situated. Master is considered as the main
branch of the project.

Consider the below output:

It will overwrite the existing data of the local repository with a remote
repository.

You can check the remote location of your repository. To check the
remote location of the repository, use the below command:

1. $ git remote -v
The given command will result in a remote location like this:

1. origin https://github.com/ImDwivedi1/GitExample2 (fetch)


2. origin https://github.com/ImDwivedi1/GitExample2 (push)

The output displays fetch and push both locations. Consider the below
image:

Git Pull Request


Pull request allows you to announce a change made by you in the branch.
Once a pull request is opened, you are allowed to converse and review the
changes made by others. It allows reviewing commits before merging into
the main branch.

Pull request is created when you committed a change in the GitHub


project, and you want it to be reviewed by other members. You can
commit the changes into a new branch or an existing branch.

Once you've created a pull request, you can push commits from your
branch to add them to your existing pull request.

How to Create a Pull Request


To create a pull request, you need to create a file and commit it as a new
branch. As we mentioned earlier in this topic, how to commit a file to use
git pull. Select the option "create a new branch for this commit and
start a pull request" from the bottom of the page. Give the name of the
new branch. Select the option to propose a new file at the bottom of the
page. Consider the below image.
In the above image, I have selected the required option and named the
file as PullRequestDemo. Select the option to propose a new file. It will
open a new page. Select the option create pull request. Consider the
below image:

Now, the pull request is created by you. People can see this request. They
can merge this request with the other branches by selecting a merged
pull request.

Git Push
The push term refers to upload local repository content to a remote
repository. Pushing is an act of transfer commits from your local
repository to a remote repository. Pushing is capable of overwriting
changes; caution should be taken when pushing.
Moreover, we can say the push updates the remote refs with local refs.
Every time you push into the repository, it is updated with some
interesting changes that you made. If we do not specify the location of a
repository, then it will push to default location at origin master.

The "git push" command is used to push into the repository. The push
command can be considered as a tool to transfer commits between local
and remote repositories. The basic syntax is given below:

1. $ git push <option> [<Remote URL><branch name><refspec>...]

Push command supports many additional options. Some options are as


follows under push tags.

Git Push Tags


<repository>: The repository is the destination of a push operation. It
can be either a URL or the name of a remote repository.

<refspec>: It specifies the destination ref to update source object.

--all: The word "all" stands for all branches. It pushes all branches.

--prune: It removes the remote branches that do not have a local


counterpart. Means, if you have a remote branch say demo, if this branch
does not exist locally, then it will be removed.

--mirror: It is used to mirror the repository to the remote. Updated or


Newly created local refs will be pushed to the remote end. It can be force
updated on the remote end. The deleted refs will be removed from the
remote end.
--dry-run: Dry run tests the commands. It does all this except originally
update the repository.

--tags: It pushes all local tags.

--delete: It deletes the specified branch.

-u: It creates an upstream tracking connection. It is very useful if you are


going to push the branch for the first time.

Git Push Origin Master


Git push origin master is a special command-line utility that specifies the
remote branch and directory. When you have multiple branches and
directory, then this command assists you in determining your main branch
and repository.

Generally, the term origin stands for the remote repository, and master
is considered as the main branch. So, the entire statement "git push
origin master" pushed the local content on the master branch of the
remote location.

Syntax:

1. $ git push origin master

Let's understand this statement with an example.

Let's make a new commit to my existing repository, say GitExample2. I


have added an image to my local repository named abc.jpg and
committed the changes. Consider the below
image:
In the above output, I have attached a picture to my local repository. The
git status command is used to check the status of the repository. The git
status command will be performed as follows:

1. $ git status

It shows the status of the untracked image abc.jpg. Now, add the image
and commit the changes as:

1. $ git add abc.jpg


2. $git commit -m "added a new image to project."

The image is wholly tracked in the local repository. Now, we can push it to
origin master as:

1. $ git push origin master

Output:

The file abc.jpg is successfully pushed to the origin master. We can track
it on the remote location. I have pushed these changes to my GitHub
account. I can track it there in my repository. Consider the below image:
In the above output, the pushed file abc.jpg is uploaded on my GitHub
account's master branch repository.

Git Force Push


The git force push allows you to push local repository to remote without
dealing with conflicts. It is used as follows:

1. $ git push <remote><branch> -f

Or

1. $ git push <remote><branch> -force

The -f version is used as an abbreviation of force. The remote can be any


remote location like GitHub, Subversion, or any other git service, and the
branch is a particular branch name. For example, we can use git push
origin master -f.

We can also omit the branch in this command. The command will be
executed as:

1. $git push <remote> -f

We can omit both the remote and branch. When the remote and the
branch both are omitted, the default behavior is determined
by push.default setting of git config. The command will be executed as:

1. $ git push -f
How to Safe Force Push Repository:
There are several consequences of force pushing a repository like it may
replace the work you want to keep. Force pushing with a lease option is
capable of making fail to push if there are new commits on the remote
that you didn't expect. If we say in terms of git, then we can say it will
make it fail if remote contains untracked commit. It can be executed as:

1. $git push <remote><branch> --force-with-lease


Git push -v/--verbose
The -v stands for verbosely. It runs command verbosely. It pushed the
repository and gave a detailed explanation about objects. Suppose we
have added a newfile2.txt in our local repository and commit it. Now,
when we push it on remote, it will give more description than the default
git push. Syntax of push verbosely is given below:
Syntax:

1. $ git push -v

Or

1. $ git push --verbose

Consider the below output:

If we compare the above output with the default git option, we can see
that git verbose gives descriptive output.

Delete a Remote Branch


We can delete a remote branch using git push. It allows removing a
remote branch from the command line. To delete a remote branch,
perform below command:

Syntax:

1. $ git push origin -delete edited

Output:
In the above output, the git push origin command is used with -delete
option to delete a remote branch. I have deleted my remote
branch edited from the repository. Consider the below image:

It is a list of active branches of my remote repository before the operating


command.

The above image displays the list of active branches after deleting
command. Here, you can see that the branch edited has removed from
the repository.

GIT Interview Questions


1) What is GIT?
Git is an open source distributed version control system and source code
management (SCM) system with an insistence to control small and large
projects with speed and efficiency.

2) Which language is used in Git?


Git uses 'C' language. Git is quick, and 'C' language makes this possible by
decreasing the overhead of run times contained with high-level
languages.
3) What is a repository in Git?
A repository consists of a list named .git, where git holds all of its
metadata for the catalog. The content of the .git file is private to Git.

4) What is 'bare repository' in Git?


A "bare" repository in Git includes the version control information and no
working files (no tree), and it doesn?t include the special. git sub-
directory. Instead, it consists of all the contents of the .git sub-directory
directly in the main directory itself, whereas working list comprises of:

1. A .git subdirectory with all the Git associated revision history of your repo.
2. A working tree, or find out copies of your project files.

5) What is the purpose of GIT stash?


GIT stash takes the present state of the working file and index and puts in
on the stack for next and gives you back a clean working file. So in case if
you are in the middle of object and require to jump over to the other task,
and at the same time you don't want to lose your current edits, you can
use GIT stash.

6) What is GIT stash drop?


When you are done with the stashed element or want to delete it from the
directory, run the git 'stash drop' command. It will delete the last added
stash item by default, and it can also remove a specific topic if you include
as an argument.

7) What are the advantages of using GIT?


Here are some of the essential advantages of Git:

o Data repetition and data replication is possible


o It is a much applicable service
o For one depository you can have only one directory of Git
o The network performance and disk application are excellent
o It is effortless to collaborate on any project
o You can work on any plan within the Git

8) What is the function of 'GIT PUSH' in GIT?


'GIT PUSH' updates remote refs along with related objects

9) Why do we require branching in GIT?


With the help of branching, you can keep your branch, and you can also
jump between the different branches. You can go to your past work while
at the same time keeping your recent work intact.

10) What is the purpose of 'git config'?


The 'Git config' is a great method to configure your choice for the Git
installation. Using this command, you can describe the repository
behavior, preferences, and user information.

11) What is the definition of "Index" or "Staging Area" in


GIT?
When you are making the commits, you can make innovation to it, format
it and review it in the common area known as 'Staging Area' or 'Index'.

12) What is a 'conflict' in git?


A 'conflict' appears when the commit that has to be combined has some
change in one place, and the current act also has a change at the same
place. Git will not be easy to predict which change should take
precedence.

13) What is the difference between git pull and git fetch?
Git pull command pulls innovation or commits from a specific branch from
your central repository and updates your object branch in your local
repository.
Git fetch is also used for the same objective, but it works in a slightly
different method. When you behave a git fetch, it pulls all new commits
from the desired branch and saves it in a new branch in your local
repository. If you need to reflect these changes in your target branch, git
fetch should be followed with a git merge. Your target branch will only be
restored after combining the target branch and fetched branch. To make
it simple for you, remember the equation below:

Git pull = git fetch + git merge

14) How to resolve a conflict in Git?


If you need to resolve a conflict in Git, edit the list for fixing the different
changes, and then you can run "git add" to add the resolved directory,
and after that, you can run the 'git commit' for committing the repaired
merge.

15) What is the purpose of the git clone?


The git clone command generates a copy of a current Git repository. To
get the copy of a central repository, 'cloning' is the simplest way used by
programmers.

16) What is git pull origin?


pull is a get and a consolidation. 'git pull origin master' brings submits
from the master branch of the source remote (into the local origin/master
branch), and then it combines origin/master into the branch you currently
have looked out.

17) What does git commit a?


Git commits "records changes to the storehouse" while git push " updates
remote refs along with contained objects" So the first one is used in a
network with your local repository, while the latter one is used to
communicate with a remote repository.
18) Why GIT better than Subversion?
GIT is an open source version control framework; it will enable you to run
'adaptations' of a task, which demonstrate the changes that were made to
the code over time also it allows you keep the backtrack if vital and fix
those changes. Multiple developers can check out, and transfer changes,
and each change can then be attributed to a particular developer.

19) Explain what is commit message?


Commit message is a component of git which shows up when you submit
a change. Git gives you a content tool where you can enter the
adjustments made to a commit.

20) Why is it desirable to create an additional commit


rather than amending an existing commit?
There are couples of reason

1. The correct activity will devastate the express that was recently saved in a
commit. If only the commit message gets changed, that's not a problem.
But if the contents are being modified, chances of excluding something
important remains more.
2. Abusing "git commit- amends" can cause a small commit to increase and
acquire inappropriate changes.

21) What does 'hooks' comprise of in Git?


This index comprises of Shell contents which are enacted after running
the relating git commands. For instance, Git will attempt to execute the
post-commit content after you run a commit.

22) What is the distinction between Git and Github?


A) Git is a correction control framework, a tool to deal with your source
code history.

GitHub is a hosting function for Git storehouses.


GitHub is a website where you can transfer a duplicate of your Git archive.
It is a Git repository hosting service, which offers the majority of the
distributed update control and source code management (SCM)
usefulness of Git just as including its features.

23) In Git, how would you return a commit that has just
been pushed and made open?
There can be two answers to this question and ensure that you
incorporate both because any of the below choices can be utilized relying
upon the circumstance:

Remove or fix the bad document in another commit and push it to the
remote repository. This is a unique approach to correct a mistake. Once
you have necessary changes to the record, commit it to the remote
repository for that I will utilize

git submit - m "commit message."

Make another commit that fixes all changes that were made in the terrible
commit. to do this, I will utilize a command

git revert <name of bad commit>

24) What does the committed item contain?


Commit item contains the following parts; you should specify all the three
present below:

A set of records, representing to the condition of a task at a given purpose


of time

References to parent commit objects

An SHAI name, a 40 character string that uniquely distinguishes the


commit object.

25) Describing branching systems you have utilized?


This question is a challenge to test your branching knowledge with Git
along these lines, inform them regarding how you have utilized branching
in your past activity and what reason does it serves, you can refer the
below mention points:
Feature Branching:

A component branch model keeps the majority of the changes for a


specific element within a branch. At the point when the item is throughout
tested and approved by automated tests, the branch is then converged
into master.

Task Branching

In this model, each assignment is actualized on its branch with the


undertaking key included in the branch name. It is anything but difficult to
see which code actualizes which task, search for the task key in the
branch name.

Release Branching

Once the create branch has procured enough features for a discharge,
you can clone that branch to frame a Release branch. Making this branch
begins the following discharge cycle so that no new features can be
included after this point, just bug fixes, documentation age, and other
release oriented assignments ought to go in this branch. When it is
prepared to deliver, the release gets converged into master and labeled
with a form number. Likewise, it should be converged once again into
creating a branch, which may have advanced since the release was
started.

At last, disclose to them that branching methodologies fluctuate starting


with one association then onto the next, so I realize essential branching
activities like delete, merge, checking out a branch, etc.

26) By what method will you know in Git if a branch has


just been combined into master?
The appropriate response is immediate.

To know whether a branch has been merged into master or not you can
utilize the below commands:

git branch - merged It records the branches that have been merged into
the present branch.

git branch - no merged It records the branches that have not been
merged.
27) How might you fix a messed up submit?
To fix any messed up commit, you will utilize the order "git commit?
correct." By running this direction, you can set the wrecked commit
message in the editor.

28) Mention the various Git repository hosting functions.


The following are the Git repository hosting functions:

o Pikacode
o Visual Studio Online
o GitHub
o GitEnterprise
o SourceForge.net

29) Mention some of the best graphical GIT customers for


LINUX?
Some of the best GIT customer for LINUX is

a. Git Cola
b. Smart git
c. Git-g
d. Git GUI
e. Giggle
f. qGit

30) What is Subgit? Why use it?


'Subgit' is a tool that migrates SVN to Git. It is a stable and stress-free
migration. Subgit is one of the solutions for a company-wide migration
from SVN to Git that is:

a. It is much superior to git-svn


b. No need to change the infrastructure that is already placed.
c. It allows using all git and all sub-version features.
d. It provides stress ?free migration experience.

You might also like