Git Detailed Learning Course


Author: gafish

Introduction to Git

GitDistributed version control system, which is not limited by network connection and has many other advantages, has become the preferred version management system for programmers, and can be used by non-developers.GitMake your own document version management tool.

In 2013, the front-end team of Taobao began to adopt it comprehensively.GitTo do project management, I also began to contact and use at that time, from zero contact at the beginning to heavy dependence now, it is really amazing.GitPowerful.

GitThere are many apis, but in fact, 90% of the requirements of projects in peacetime only need to use a few basic functions, so this article will be from.pragmatismAndDeep explorationTwo aspects to talk about how to use it in a projectGitGenerally speaking, after reading.pragmatismThis section can be started in the project.

Note: The operation of this paper is based on Mac system.


Preparatory phase

Go to the Git website to download your installation package. The current version I downloaded is ___________.2.11.0This article will also demonstrate the effect in this version.


InstalledGitAfter that, open the command line tool and enter the working folder(For ease of understanding, we demonstrated it on the system desktopCreate a new demo folder.


Enter the Github website to register an account and log in. Enter:

ClickClone or downloadClick againUse HTTPSCopy the project address:


Back to the command line tools, everything is ready, and then to the focus of this article.

Common Operations

The so-called pragmatism is that you can play with the following knowledge.GitEasy to deal with more than 90% of the demand. Here’s a list of pragmatic Git commands. Let’s take a look at them first.

  • git clone

  • git config

  • git branch

  • git checkout

  • git status

  • git add

  • git commit

  • git push

  • git pull

  • git log

  • git tag

Next, we will go through

The warehouse carries on the example operation, explains how to use.GitPull the substitution code to the entire process of submitting the code.

git clone

Pull substitution code from git server

git clone

There will be one in the current folder when the code download is completed.gafish.github.comThe catalogue, adopted by _____________cd gafish.github.comCommand to enter the directory.

git config

Configure developer usernames and mailboxes

git config gafishgit config [email protected]

Each code submission generates a submission record containing the currently configured username and mailbox.

git branch

Create, rename, view and delete project branches.GitWhen doing project development, it is usually carried out in the development branch. After the development is completed, the branch is merged into the backbone.

git branch daily/0.0.0

Create a name calleddaily/0.0.0Daily branch development, branch name as long as does not include special characters.

git branch -m daily/0.0.0 daily/0.0.1

If you feel that the previous branch name is inappropriate, you can rename the new branch and rename the branch name.daily/0.0.1

git branch

You can view the current project branch list by using the non-parametric branch command

git branch -d daily/0.0.1

If the branch has completed its mission, it can do so by ____________-dParametric will delete the branch. In order to continue the next step, delete operation will not be executed for the time being.

git checkout

Switching branch

git checkout daily/0.0.1

Switch todaily/0.0.1Branch, on which subsequent operations will take place

git status

View File Change Status

Use any editor you like to work with on the project’s ____________README.mdMake some changes to the document and save it.

git status

Bygit statusThe command can see the current state of the file.Changes not staged for commit: (Change document not submitted to temporary storage area

On branch daily/0.0.1Changes not staged for commit:  (use "git add <file>..." to update what will be committed)  (use "git checkout -- <file>..." to discard changes in working directory)    modified:   README.mdno changes added to commit (use "git add" and/or "git commit -a")

git add

Add File Change to Temporary Zone

git add

By specifying the file nameREADME.mdYou can add this file to the temporary area if you want to add all files available.git add .Orders, which can be passed at this timegit statusSee the current status of the fileChanges to be committed: (The document has been submitted to the temporary storage area.

On branch daily/0.0.1Changes to be committed:  (use "git reset HEAD <file>..." to unstage)    modified:

git commit

Change submission file to version Library

Git commit-m'Write the reason for submission here'

By-mParameters can enter submission description text directly from the command line

git push

Push local code changes to the server

git push origin daily/0.0.1

originThis command refers to the current git server address.daily/0.0.1Branches are pushed to the server, and when you see that the command line returns the following characters, the push is successful.

Counting objects: 3, done.Delta compression using up to 8 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 267 bytes | 0 bytes/s, done.Total 3 (delta 1), reused 0 (delta 0)remote: Resolving deltas: 100% (1/1), completed with 1 local objects.To * [new branch]      daily/0.0.1 -> daily/0.0.1

Now let’s go back to the project home page of Github and clickBranch:masterPull down the button and you’ll see what you just pushed.daily/00.1Branched

git pull

Pull the latest code from the server locally

git pull origin daily/0.0.1

If other project members make changes to the project and push them to the server, we need to update the latest changes locally. Let’s simulate this situation here.

Go to the project home page of Github website, and then enterdaily/0.0.1Branch, online pairingREADME.mdMake some changes to the file and save it. Then execute the above command in the command. It will pull the online modification part to the local area and open it with the editor.README.mdYou will find that the file has been synchronized with the online content.

If the online code changes and your local code changes, the pulled code may conflict with your local changes.GitConflict merges are automatically handled, but if the changes are in the same line, you need to merge the code manually, edit the file, save the latest changes, and then pass them.git add .Andgit commit -m 'xxx'To submit mergers.

git log

View version submission records

git log

With the above commands, we can view the version submission record of the entire project, which containssubmitterdateReasons for submissionThe results are as follows:

commit c334730f8dba5096c54c8ac04fdc2b31ede7107aAuthor: gafish <[email protected]>Date:   Wed Jan 11 09:44:13 2017 +0800    Update README.mdcommit ba6e3d21fcb1c87a718d2a73cdd11261eb672b2aAuthor: gafish <[email protected]>Date:   Wed Jan 11 09:31:33 2017 +0800    test.....

There may be a lot of submissions, press ___________.JTurn down the key and press the ____________ button.KTurn the key up and press the ____________ button.QKey Exit View

git tag

Mark milestones for projects

git tag publish/0.0.1git push origin publish/0.0.1

When we are ready to release a functional requirement, we should mark the complete project code and publish the marked version online.publish/0.0.1For tag name and publication, when you see the command line return the following, the publication is successful

Total 0 (delta 0), reused 0 (delta 0)To * [new tag]         publish/0.0.1 -> publish/0.0.1


Setting what doesn’t need to be pushed to the server is a configuration file

touch .gitignore

.gitignoreNo.GitCommand, and a file in the project, by setting.gitignoreContent informGitWhich files should be ignored and need not be pushed to the server to create one with the above commands.gitignoreFile and open the file in the editor. Each line represents a file or directory to be ignored, such as:


The meaning of the above is ____________.GitIt will be overlooked.demo.htmlDocumentation andbuild/Directory, which is not pushed to the server


By mastering these basic commands, you can start to use them in the project. If you want to be practical, then about.GitThis is the end of learning, and the occasional problems are basically passed.GoogleThe answer can also be found if you want to explore further.GitHigh-level functionality, so keep looking down.Deep explorationPart.

Deep exploration

Basic concepts

Workspace(Working Directory

It’s the directory you can see on your computer, like the one above.gafish.github.comA folder is a workspace


Local Version Library(Local Repository

The workspace has a hidden directory.gitThis is not a workspace, but a workspace.GitVersion library.


Temporary storage areastage

There are a lot of things in the local version library, the most important of which is called __________.stage(or index) the temporary storage area, as well as _____________GitThe first branch created automatically for usmasterAnd pointing to the _____________masterA pointer is calledHEAD

Remote Version Library(Remote Repository

Generally speaking,GitThe corresponding warehouse on the server, where the example in this article is locatedgithubA repository is a remote version repository


The relationship between the above concepts

work areaTemporary storage areaLocal Version LibraryRemote Version LibrarySeveral commonly usedGitThe operation process is shown in the following figure:



Branching is to store the whole process of modifying records separately so that the separate branches are not affected by other branches, so different modifications can be made simultaneously in the same database.


Main branch(Master

As mentioned earlier,masterYesGitThe first branch created automatically for us, also known as the main branch, will be merged into the other branches when they are developed.master



Tags are used to mark specific points or submitted history, and are usually used to mark the name or version number of a publication (e.g.publish/0.0.1Although the label looks a bit like a branch, the labeled submission is fixed and can not be changed at will. See the figure above.1.0 / 2.0 / 3.0


HEADTo point to the latest submission of the current branch


The above concepts are similar, so we can continue to look at them. The following will explain the specific types of operation.GitHigher-order usage

Operational Documents

git add

Add Files to Temporary Zone

git add -i

This command will open the interactive subcommand system, and you will see the following subcommands

***Commands***  1: status      2: update      3: revert      4: add untracked  5: patch      6: diff      7: quit      8: help

The corresponding functions can be selected by inputting serial numbers or initials. The specific functions are explained as follows:

  • statusFunctionally andgit add -iSimilarly, it’s no use for birds.

  • updateSee below for details.git add -u

  • revertDocuments that have been added to the temporary area are removed from the temporary area, and how they are operated.updateSimilar

  • add untrackedAdditional files can be added to the temporary storage area, and how they are operated.updateSimilar

  • patchSee below for details.git add -p

  • diffCompare the differences between temporary area files and local version libraries, and their operation methods.updateSimilar

  • quitWithdrawalgit add -iCommand System

  • helpView Help Information



git add -p

Direct access to interactive commands is the most usefulpatchModel

This is the most useful pattern for interactive commands, and how it works.updateSimilarly, after selectionGitThe differences between the current contents of these files and the local version libraries are displayed, and then you can decide for yourself whether to add these changes to the temporary area, at the command line.Stage deletion [y,n,q,a,d,/,?]?Post-inputy,n,q,a,d,/,?One of the options is the mode of operation. The specific functions are explained as follows:

  • Y: Accept modifications

  • N: Ignore modifications

  • Q: Exit the current command

  • A: Add modifications

  • D: Abandon modification

  • / Modify content by matching regular expressions

  • ?: Check out help information



git add -u

Direct access to interactive commandsupdateModel

It lists the workspaces first.modifyOrdeleteList of documents,Newly addedThe file will not be displayed on the command line.Update>>Enter the corresponding list serial number to indicate that the item is selected, return to continue to select, if selected, return directly to the main command interface

git add --ignore-removal .

Adding workspacesmodifyOrNewly addedList of documents,deleteDocuments will not be added

git commit

Submit files from the temporary storage area to the local version Library

Git commit-m'first line submission reason'- M' second line submission reason'

Instead of opening the editor, enter the multi-line commit reason directly from the command line

Git commit-am'submission reason'

WorkspacemodifyOrdeleteDocuments are submitted to the local version library.Newly addedDocuments will not be submitted

Git commit -- amend-m'submission reason'

Reasons for submitting a revised latest submission record

git commit -C HEAD

Submit current file changes toHEADOr the historical ID of the current branch

git mv

Move or rename files, directories

git mv -f

Willa.mdRenamedb.mdAt the same time, add changes to the temporary storage area, add-fParameters can be renamed b.mdThe order was omitted.git addOperation

git rm

Remove files from workspace and temporary area

git rm

Remove files from workspace and temporary storage areab.mdAt the same time, add changes to the temporary storage area, compared with the use of __________.rm b.mdThe order was omitted.git addOperation

git rm src/ -r

Allow directories to be removed from workspaces and temporaries

git status

git status -s

View the status of workspace and temporary area files in a short way. Examples are as follows:

M demo.html?? test.html
git status --ignored

View the status of workspace and temporary area files, including overlooked files

Operational branch

git branch

View, create, and delete branches

git branch -a

View branch lists on local and remote version Libraries

git branch -r

View the list of branches on the remote version library, and add ____________-dParameters can delete branches on remote version Libraries

git branch -D

Forcibly delete branches before they are submitted to the local version Library

git branch -vv

View a branch list of local version libraries with final submission id, reasons for recent submissions, and so on


git merge

Merge other branches into the current branch

git merge --squash

Will be merged on the branch of _____________commitMerge into a newcommitPut it into the current branch, which is suitable for submission records of merged branches that need not be retained


git merge --no-ff

By default,GitImplementation“Fast Forward Merger“(fast-farward merge), will directlyMasterBranch orientationDevelopBranch, use--no-ffAfter the parameter, the normal merge will be performed, and the merge will be executed in _________.MasterGenerate a new node on the branch to ensure a clearer version evolution.


git merge --no-edit

Merge without conflict. Instead of manually editing the submission reasons, useGitSimilar to automatic generationMerge branch 'test'Direct submission of text

git checkout

Switching branch

git checkout -b daily/0.0.1

Createdaily/0.0.1Branch and switch to the newly created branch at the same time

git checkout HEAD demo.html

From the local version LibraryHEAD(You can also submit ID, branch name, Tag name) checked out in historydemo.htmlOverwrite files in the current workspace if omittedHEADIt was detected from the temporary storage area.

git checkout --orphan new_branch

This command will create a new branch with no history at all, but all the latest documents on the current source branch are still there. It’s good news for obsessive-compulsive disorder patients, but this new branch must be done once.git commitIt will become a new branch after operation.

git checkout -p other_branch

This command is mainly used to compare the differences between the two branches, and provides an interactive interface to select further operations. This command can not only compare the differences between the two branches, but also compare the differences between individual files.

git stash

InGitKeep the current progress of modification or deletion in the stack. When you do a function development in a branch, you are notified to release the code that was tested yesterday, but at this time you have added other uncommitted code to the branch, and then you can put the uncommitted code on the line. Store it in the stack.

git stash

Save uncommitted files to the Git stack

git stash list

View the list saved on the stack

git stash show [email protected]{0}

Display one of the records on the stack

git stash drop [email protected]{0}

Remove one of the records from the stack

git stash pop

Check out the latest saved record from the Git stack and remove it from the stack

git stash apply [email protected]{0}

One of the records was detected from the Git stack, but not removed from the stack

git stash branch new_banch

Check out the last record on the current stack and create a new branch

git stash clear

Empty all records in the stack

git stash create

Create a custom stack for the currently modified or deleted files and return an ID, which is not actually stored on the stack

git stash store xxxxxx

WillcreateThe ID returned from the method is placed in the ____________storeLater, a record is actually created in the stack at this point, but the currently modified or deleted files are not removed from the workspace

$ git stash create09eb9a97ad632d0825be1ece361936d1d0bdb5c7$ git stash store 09eb9a97ad632d0825be1ece361936d1d0bdb5c7$ git stash [email protected]{0}: Created via "git stash store".

Operational History

git log

Display submission history

git log -p

Display historical records with submission differences comparison

git log demo.html

Displaydemo.htmlHistorical records of documents

git log --since="2 weeks ago"

It shows the historical records from two weeks ago to the present. Analogy can be made at other times.

git log --before="2 weeks ago"

Display the history up to 2 weeks ago. Analogy can be made at other times.

git log -10

Display the last 10 historical records

git log f5f630a..HEAD

Display from submission IDf5f630aToHEADRecords between,HEADID can be submitted for null or other purposes

git log --pretty=oneline

Output a short history in a row

git log --pretty=format:"%h"

Format output history

GitUse a variety of _____________placeholderTo determine various display contents, I choose several commonly used displays as follows:

  • %H: commit hash

  • % h: Shortened commit hash

  • %T: tree hash

  • % t: Shortened tree hash

  • %P: parent hashes

  • % p: Shortened parent hashes

  • % an: Author’s name

  • % aN: Author name of mailmap

  • % ae: Author’s mailbox

  • % ad: Date (–date = format)

  • % ar: Date, relative format (1 day ago)

  • % cn: Submitter name

  • % ce: submitter email

  • % cd: Submission date (- date = format)

  • % cr: submission date, relative format (1 day ago)

  • % d: ref name

  • % s: Commit Information Title

  • % b: commit information content

  • % n:Line Break

git cherry-pick

One or more submissions of a merged branch are recorded at the end of the current branch

git cherry-pick 170a305

Merge submission ID170a305To the end of the current branch

git reset

Reset the current branch to the specified<commit>OrHEAD

git reset --mixed <commit>

--mixedThe default parameter without parameters, which returns to a version, retains the file content, and returns the submission history

git reset --soft <commit>

The contents of the temporary and workspace are unchanged, but only changed.HEADDirection<commit>

git reset --hard <commit>

Since<commit>Since then, any changes in the workspace have been discarded.HEADDirection<commit>

git rebase

Redefining Branch Version Library Status

git rebase branch_name

Merge branches, this is the same as ___________.mergeIt’s very similar, but there are essential differences. Look at the following picture:


Conflicts may need to be resolved before they are executed in the merger process.git rebase --continue

git rebase -i HEAD~~

Open the text editor and you will see fromHEADToHEAD~~Submitted as follows

Pick 9a54fd4 Adding Commit Description Pick 0d4a808 Adding pull Description Rebase 326fc9f. 0d4a808 On d286baa Commands: p, pick = use commit r, reword = use commit, but edit message the commit e, edit = use, but commit for committing stop # use = use Commit, but meld into previous commit f, fixup = like "squash", but discard this commit's log message x, exec = run command (the rest of the line) using shell#

In the first linepickChange to _____________CommandsThe commands listed in this list are then saved and exited, and the corresponding modifications will take effect.

If you move the order in which records are submitted, the sort in the history will be changed.

git revert

Revoke an operation before and after the operationcommitAndhistoryAll will retain and make this withdrawal an up-to-date submission

git revert HEAD

Revoke previous submission

git revert HEAD --no-edit

Revoke previous submission and defaultRevert "xxx"For reasons of submission

git revert -n HEAD

When multiple operations need to be revoked, add-nParameters, so that not every revocation is committed, but when all revocations are completed

git diff

View file differences among workspaces, temporary areas, and local version libraries, and use a diagram to explain them


git diff --stat

By--statParameters allow you to view change statistics | 1 - 1 file changed, 1 deletion(-)

git reflog

reflogYou can view all operation records of all branches (including commit and reset operations, deleted commit records, andgit logThe difference is that it cannot view deleted commit records


Remote Version Library Connection

If the file already exists in the local directory before the GitHub project is initialized, the local version library can be initialized locally, and then the local version library can be connected to the remote version library.

git init

The. git folder is generated within the local directory

git remote

git remote -v

List the remote branches that already exist without parameters, and add _____________-vList the details and the remote URL after each name

git remote add origin

Add a new remote warehouse and specify a name to refer to the following URL

git fetch

Retrieve updates from remote version libraries back to local version Libraries

git fetch origin daily/0.0.1

By default,git fetchRetrieve updates from all branches. If you only want to retrieve updates for a particular branch, you can specify the branch name.

Problem investigation

git blame

View the history of each line of code block in a file

git blame -L 1,10 demo.html

Interceptiondemo.html1-10 lines of historical information in the document

git bisect

Binary Search for Historical Records, Search for BUG

git bisect start

Start Binary Search

git bisect bad

Mark the current bipartite submission ID as a problematic point

git bisect good

Mark the point where the current bipartite submission ID is OK

git bisect reset

Return to the original branch after finding a problem with the submission ID

More operations

git submodule

External version libraries can be tracked through Git sub-modules, which allow another version library to be stored in one version library and keep two version libraries completely independent.

git submodule add demo

WilldemoWarehouse added as sub-module

git submodule update demo

Update submoduledemo

git gc

Running Git’s garbage collection function to clean up redundant historical snapshots

git archive

Packing and extracting a version with tag

git archive -v --format=zip v0.1 >

--formatRepresents the format of the package, such aszip-vRepresents the corresponding tag name followed by the tag name, such asv0.1


This article is just right.GitGit is very powerful, and there are many other functions to be found. As far as the length of this article is concerned, let’s stop here and predict more useful functions. Please make good use of Google.

Reference material









PUSHRecommendationReadread(Click to jump to read)

1.SpringBook content aggregation

2. Content aggregation of interview questions

3. Design pattern content aggregation

4. Mybatis content aggregation

5. Multithread Content Aggregation

Recommended Today

The construction tool of C ා

What’s the motivation for writing this article? Why do you want to study the build tool (see. Csproj), create a new C project with visual studio IDE, and click build to run it? A: please refer to this_minutes_before_coding. I call it “engineering.”. Engineering development is not just about opening IDE and creating new projects. It […]