A long article on git Foundation


A long article on git Foundation

Version management is a very important part in product development, which involves team cooperation and affects the final release, launch and testing of the product. Git is the most popular version control system. Git content is very much, this article tries to introduce the basic content of GIT


The function of version control system

Version control system is a system that records the revision records of several files. It has the following three functions:

1. Rollback from current version to any version

A long article on git Foundation

2. View historical versions

A long article on git Foundation

3. Compare the differences between the two versions

A long article on git Foundation

Git advantage

1. Fast

2. The design is simple

3. Lightweight branch operation, allowing thousands of parallel development branches, strong support for non-linear development mode

4. Have the ability to efficiently manage large-scale projects similar to Linux kernel

5. Git has become the de facto standard, and almost all excellent front-end projects are version controlled by GIT

6. The community is mature and active, and the popularity of Git is inseparable from the contribution of GitHub

Important concepts

To understand git, we must first understand the important concepts in GIT

[terms introduction]

Track tracking
Stage staging
Commit commit
Push push
Pull pull
Conflict conflict
Reflog reflow

.git[table of contents]

Each project has a git directory (if any)git cloneIf it comes out, it’s one of them.gitThis is where git keeps the metadata and object database. This directory is very important. Every time you clone the image warehouse, you actually copy the data in this directory

[three states]

For any file, there are only three states in Git: committed, modified and staged

Committed: the file has been safely saved in the local database
Modified: a file has been modified but has not yet been submitted for saving
Temporary storage: put the modified files in the list to be saved at the next submission

The three states of culture correspond to the three working areas of file circulation: git working directory, temporary storage area, and local warehouse

A long article on git Foundation

Here are three working areas

The working directory is extracted independently from a certain version of the project

The staging area is a simple file, which is usually placed in the.gitIn the directory. Sometimes people call this file an index file

Local warehouse is what I mean.gitcatalog

The basic git workflow is as follows:

1. Modify some files in the working directory

2. Take a snapshot of the modified file and save it to the temporary storage area

3. Submit the update and permanently dump the file snapshot saved in the staging area to the GIT directory

[commit hash value]

Before saving to git, all data should be checked and calculated, and the result should be used as the unique identification and index of the data, not the file name

Using GitSHA-1The algorithm calculates the check sum of the data, and calculates a SHA-1 hash value as the fingerprint string through the content of the file or the structure of the directory. The string is composed of 40 hexadecimal characters (0-9 and A-F) and looks like:


Git configuration

Configuration level

Git has three configuration levels

--Local [default, high priority]: only affects this warehouse. The file is. Git / config

  --Global [medium priority]: git repository that affects all current users. The file is ~ /. Gitconfig

  --System [low priority]: affects the GIT warehouse of the whole system, and the file is / etc / gitconfig

Basic configuration

Generally, in a new system, you need to configure your own git working environment first. The configuration work only needs one time, and the current configuration will be used in future upgrades. Of course, if necessary, you can modify the existing configuration with the same command at any time

1. User name

git config --global user.name "xiaohuochai"

2. Mailbox

git config --global user.email "[email protected]"

3. Text editor

git config --global core.editor "code --wait"

4. Change the way git handles end of line bars

Windows uses carriage return (CR) and line feed (LF) to end a line, while Mac and Linux only use line feed (LF). The following code tells git to convert carriage return and line feed to line feed when submitting, and not when checking out. In this way, carriage return and line feed will be retained in the check-out file on windows, while line feed will be retained on MAC and Linux, as well as in the version library

git config --global core.autocrlf input

5. Cancel the escape of Chinese

When using git, some Chinese file names or paths are often escaped to XXXXXX. The default escape can be changed through the following configuration

git config --global core.quotepath false

6. Only push the current branch to the remote branch with the same name is allowed

git config --global push.default simple

View configuration

Git config -- list # view all configurations
Git config -- List -- global view global configuration
git config  user.name  #View a configuration item

If you want to delete or modify the configuration, a simpler way is to open it directly~/.gitconfigDocuments, or.git/configThe file can be modified

About ignored configuration

Generally, there are always some files that don’t need to be managed by git, and they don’t always appear in the list of untracked files

You can create a file named.gitignoreList the file modes to ignore

file.gitignoreThe format specification of is as follows:

1. All empty lines or lines beginning with the comment symbol are ignored by GIT

2. Standard glob pattern matching can be used

3. The matching pattern starts with a backslash (/) to prevent recursion

4. At the end of the matching pattern, a backslash (/) indicates that the directory should be ignored

5. To ignore files or directories outside the specified mode, you can reverse the mode by adding an exclamation mark (!)

.gitignoreThe common file settings are as follows


SSH configuration

If you want to do remote operation, that is, push and pull code from GitHub remote server, you need to solve a problem, that is, how does GitHub know that I am submitting my code?
In addition to entering the user name and password each time, a simpler way is to configure SSH

Most git servers choose to use SSH public key for authorization. Each user in the system must provide a public key for authorization

First, make sure you have a public key. The SSH public key is stored in the main directory of the account by default~/.sshDirectory. The file with. Pub suffix is the public key, and the other file is the key

Then, use the following command to generate SSH key, and then press enter all the way to use the default value

$ ssh-keygen -t rsa -b 4096 -C [email protected]

If all goes well, it can be found in the user’s home directory.sshCatalog. It’s got itid_rsaandid_rsa.pubThese two files are the secret key pair of SSH key,id_rsaIt’s a private key. It can’t be disclosed,id_rsa.pubIt’s a public key that you can confidently tell anyone

The public key of SSH is as follows:

$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3ltgCdqTIrPuN6yMYCeSMg8shtM+TRBIULDmfeh/9lE51e2g2t8ytLxz/QrPu3jvvpBqMimyPxC0NyW38eIHP9dkXTS0V76LlXy1MZvIjP3SnaU3AJs/fke61wc9y9EdPfrpSjIZpG7Z134+huaioLhPRShRmUQjl3plC9a89fnCyzTmtix5fDKKFjU3ZU6uVSDPy8+o+vsTfwAPQ1ylaBbY733Y1shmd6Texwmb8ttkv1Xj31RdhTdSS2eI3pSN/Ld1GC6/d2u3zcLnC6T4+1WLd0KTm/lqdzB2uWSsnMBI11wfKdw3pqEI17oGrPxurmunoMPzyR/dHwkfwotwh [email protected]

Next, log in to GitHub and open theSettingsInSSH Keyspage

A long article on git Foundation

And then, a little bitNew SSH Key, fill in any title and paste it in the key text boxid_rsa.pubContents of the document

clickAdd SSH keyButton, the configuration is complete

Next, use thessh -T [email protected]To test whether SSH is configured successfully

$ ssh -T [email protected]
Hi littlematch0123! You've successfully authenticated, but GitHub does not provide shell access.

Back to the first question in this section, how do I know that the other party is GitHub when I request code? You also need GitHub to provide me with a public key, so when you connect to GitHub for the first time, you should select Yes to accept the public key of the other party, which is the following code

$ ssh -T [email protected]
The authenticity of host 'github.com (' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
warning: Permanently added 'github.com' (rsa) to the list of known hosts
Hi littlematch0123! You've successfully authenticated, but GitHub does not provide shell access.

Git basic operation

Initialize new warehouse

To start git management for an existing project, you only need to execute git in the directory where the project is located

$ git init

After initialization, a file named.gitAll the data and resources required by git are stored in this directory. However, at present, all the files and directories are initialized according to the existing structure framework, but none of the files in the project has been tracked and managed

Check file status

To determine which files are currently in what state, you can use thegit statuscommand

If you execute this command immediately after getting the warehouse, you will see output like this

$ git status
On branch master
Initial commit
nothing to commit(create/copy files and use "git add" to track)

This shows that the current working directory is quite clean. In other words, none of the tracked files has been changed since the last time they were submitted, or there are no files

Now create a new file readme, save it, exit and run itgit statusYou will see the file appear in the list of untracked files

$ git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)


nothing added to commit but untracked files present (use "git add" to track)

In the status report, you can see that the newly created readme file appears under “untracked files”. Untracked files means git did not have them in the previous snapshot (COMMIT)

Track new files

Using commandsgit addStart tracking a new file. So, to track the readme file, run

$ git add README.txt

Using commandsgit add .It will batch track all the untracked files in the working directory

$ git add .

Run again at this timegit statusCommand, you will see that the readme file has been tracked and is in the staging state

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   README.txt

As long as it is under the line “changes to be committed”, it means that it is in the staged state

Staging modified files

Now modify the previously tracked file README.txt And change its content to Hello world

Then run the status command again, and you will see such a status report:

$ echo hello world > README.txt
$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   README.txt

Changes 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.txt

file README.txt It appears under the line “changes not staged for commit”, indicating that the contents of the tracked file have changed, but have not been put into the staging area. To hold the update temporarily, you need to run the GIT add command

Git add command is a multi-functional command. According to the state of the target file, the effect of this command is different: it can be used to start tracking new files, or to put the tracked files into the temporary storage area, and it can also be used to mark the conflicting files as resolved state when merging

Therefore, it is more appropriate to interpret this command as “add content to the next submission” rather than “add a file to the project”

Run it nowgit addtake README.txt Put it in the scratch pad, and then look at the output of GIT status

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   README.txt

Submit update

Use thegit statusLet’s see if all of them have been stored, and then run the submit commandgit commit

$ git commit

In this way, the text editor will be started to input the description of this submission, and the editor will display text information similar to the following

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Initial commit
# Changes to be committed:
#    new file:   README.txt
# Changes not staged for commit:
#    modified:   README.txt

As you can see, the default submit message contains the last rungit statusIn addition, there is an empty line at the beginning, which needs to input the submission description

It can also be used-mParameter followed by the way to submit the description, submit the update in a single command line

$git commit - M 'update readme content'
[Master 34c5aa0] update readme content
 1 file changed, 1 insertion(+), 1 deletion(-)

After submission, it will prompt which branch (Master) is currently submitted, what is the full SHA-1 check sum (34c5aa0) of this submission, and how many files have been revised, and how many lines have been added or deleted in this submission

At the time of submission, givegit commitadd-aOption, GIT will automatically save all the tracked files and submit them together

$git commit - am 'update readme'
Update Readme
 1 file changed, 1 insertion(+), 1 deletion(-)

But, skipgit addStep, does not mean not to use at allgit add. becausegit commit -aIs to save and submit all the tracked files, only omitting the step of temporary storage. But a file that does not track the status needs to be usedgit addCommand to make it a tracked state

Another way to submit is to use the-vor--verboseOption, translated into Chinese is redundant, it can not only review the content just modified, but also force the submission reasons to be written in more detail

Remove 12345 from readme content
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#    modified:   README.txt
# ------------------------ >8 ------------------------
# Do not modify or remove the line above.
# Everything below it will be ignored.
diff --git a/README.txt b/README.txt
index 5c1d8ad..95d09f2 100644
--- a/README.txt
+++ b/README.txt
@@ -1 +1 @@
-hello world12345
\ No newline at end of file
+hello world
\ No newline at end of file

The results are as follows

$ git commit --verbose
[Master 2494a62] remove 12345 from Readme
 1 file changed, 1 insertion(+), 1 deletion(-)

Git view

Status overview

git statusThe output of the command is very detailed, but its language is a little cumbersome. If usedgit status -sCommand orgit status --shortCommand, will get a more compact format output

$ git status -s
 The M readme # file has been modified, but it has not been put into the staging area
Mm rakefile # was modified in the workspace after it was modified and submitted to the staging area
A  lib/ git.rb  #Files newly added to the staging area
M  lib/ simplegit.rb  #The file was modified and put into the staging area
??  LICENSE.txt  #Newly added untracked files

In general,-sOptions and-bOptions,sFor summary,bOn behalf of branch

$ git status -sb
## master...origin/master [ahead 1]
 M "git.md"

Status overview

If you know which line has changed, usegit diffcommand

git diffThe command compares the differences between the current file in the working directory and the snapshot of the staging area, that is, the changes that have not been staged after modification. If all the updated files have been staged, the command will rungit diffThere will be nothing after that

In the following code, README.txt The content of the file changes from ‘hello world1’ to ‘hello world123’

$ git diff
diff --git a/README.txt b/README.txt
index 62b372b..6d7f756 100644
--- a/README.txt
+++ b/README.txt
@@ -1 +1 @@
-hello world1
\ No newline at end of file
+hello world123
\ No newline at end of file

If you want to see the difference between the file that has been staged and the snapshot that was last submitted, you can use thegit diff--cachedcommand

In the following code, README.txt The content of the file changes from empty to ‘hello world1’

$ git diff --cached
diff --git a/README.txt b/README.txt
new file mode 100644
index 0000000..62b372b
--- /dev/null
+++ b/README.txt
@@ -0,0 +1 @@
+hello world1
\ No newline at end of file

View submission history

usegit logCommand to view the submission history

$ git log
commit 3f7b9ed403e6d624651014a5d15c481463572c15 (HEAD -> master)
Author: xiaohuochai <[email protected]>
Date:   Sun Dec 29 23:19:44 2019 +0800

    add b

commit ee5ae6f1dd5f620f4d2ac4a3702eb4814a062fce
Author: xiaohuochai <[email protected]>
Date:   Sun Dec 29 23:15:10 2019 +0800

    delete c

If no parameters are used by default,git logAll the updates will be listed according to the submission time. The most recent updates are at the top. Each update has a SHA-1 check sum, the author’s name and e-mail address, the submission time, and finally indents a paragraph to show the submission description

We often use it-pOptions to display the content differences of each submission-2Only the last two updates are displayed

$ git log -p -2
commit 3f7b9ed403e6d624651014a5d15c481463572c15 (HEAD -> master)
Author: xiaohuochai <[email protected]>
Date:   Sun Dec 29 23:19:44 2019 +0800

    add b

diff --git a/b1 b/b1
new file mode 100644
index 0000000..e69de29

commit ee5ae6f1dd5f620f4d2ac4a3702eb4814a062fce
Author: xiaohuochai <[email protected]>
Date:   Sun Dec 29 23:15:10 2019 +0800

    delete c

diff --git a/c b/c
deleted file mode 100644
index e69de29..0000000

In addition to displaying the basic information, this option also comes with the change of each commit. This parameter is useful for code reviews, or for a quick look at changes to a commit submitted by a partner

You can use it--onelineOption displays each submission on a line, which is useful when the number of submissions is large

$ git log --oneline
3f7b9ed (HEAD -> master) add b
ee5ae6f delete c

Git command history

git reflogThe order follows all the previous stepscommitPaths are arranged in order to record each command, which is often used in the auxiliary operation of version switching

$ git reflog

Git version switch

In order to switch versions, GIT must know which version is the current version. In git, usingHEADTo represent the current version, that is, the latest submission, and the last version isHEAD^The last version wasHEAD^^Of course, it’s easier to write 100 ^ in 100 versions, so it’s writtenHEAD~100

Use firstgit log --onlineLet’s take a look at the current submission history

$ git log --oneline
e7422c8 (HEAD -> master) add b
ee5ae6f delete c
8760a0f add c

Using commandsgit reset --hard commit_idSwitch between versions’ history

 git reset --hard HEAD^
HEAD is now at ee5ae6f delete c

Reusegit log --onlineA brief review of the submission history shows that the latest version is no longer available

$ git log --oneline
ee5ae6f (HEAD -> master) delete c
8760a0f add c

What if you find the latest version of the submitted object? Git provides a commandgit reflogThe command follows all previous stepscommitThe paths are arranged in order to record each command

$ git reflog
ee5ae6f (HEAD -> master) [email protected]{0}: reset: moving to HEAD^
e7422c8 [email protected]{1}: commit (amend): add b
3f7b9ed [email protected]{2}: commit: add b
ee5ae6f (HEAD -> master) [email protected]{3}: commit: delete c
8760a0f [email protected]{4}: commit: add c

fromgit reflogIn the result returned by the command, e7422c8 is the latest version of commit ID

Use belowgit reset --hardCommand to restore the file to the latest version

$ git reset --hard e7422c8
HEAD is now at e7422c8 add b

Git branch management

Almost every version control system supports branching in some way. Using branching means that you can separate from the development mainline and continue to work without affecting the mainline.

In fact, the branch in Git is only a variable pointer to the commit object, that is, a file containing the checksums of the objects it refers to (40 character SHA-1 string). Therefore, it is very cheap to create and destroy a branch. To put it bluntly, a new branch is as simple as writing 41 bytes (plus a newline character) to a file. Of course, it’s very fast

Git will use master as the default name of the branch. After several submissions, there is actually a master branch pointing to the last submitted object, which will automatically move forward each time it is submitted

A long article on git Foundation

Create branch

Create a new branch pointer. For example, to create a new testing branch, you can use thegit branchcommand

$ git branch testing

This will be in the current situationcommitObject to create a new branch pointer

A long article on git Foundation

Git holds a special pointer called head, which is a pointer to the local branch that is working (think of head as an alias for the current branch). functiongit branchCommand only creates a new branch, but it will not automatically switch to this branch, so in this example, it is still theremasterWorking in a branch

Switch branches

To switch to another branch, you can perform thegit checkoutOrders. Now switch to the new onetestingBranch, so head points totestingbranch

$ git checkout testing

A long article on git Foundation

git checkoutuse-bOption, you can create a new branch and switch to it, such as iss53 branch

$ git checkout -b iss53

Merge branches

have access togit mergeCommand to achieve branch merging. Generally, there are three cases of merging branches

1. Fast forward merge

If the submitted object of the current master branch is directly upstream of the hotfix branch to be merged, GIT only needs to move the master branch pointer directly to the right. In other words, if you can go down one branch to reach another branch, GIT will simply move the pointer to the right when merging the two. Because there is no difference to be solved in this single line historical branch, this merging process can be called fast forward

$ git checkout master
$ git merge hotfix
Updating f42c576..3a0874c
 README | 1 -
 1 file changed, 1 deletion(-)

2. Conflict free merge

As shown in the figure below, to merge the issue 53 branch back into the master branch, GIT will use the ends of the two branches (C4 and C5) and their common ancestor (C2) for a simple three-way merge

A long article on git Foundation

$ git checkout master
$ git merge iss53
Auto-merging README
Merge made by the 'recursive' strategy.
 README | 1 +
 1 file changed, 1 insertion(+)

Git makes a new snapshot of the combined results of the three parties, and automatically creates a commit object (C6) pointing to it. This submission object is special. It has two ancestors (C4 and C5)

A long article on git Foundation

3. Conflicted merge

If you change the same part of the same file in different branches, GIT can’t put the two together cleanly (logically, this kind of problem can only be decided by people). If the modified part in hotfix is modified in the process of solving the problem, the result will be similar to the following

$ git merge iss53
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.

Git merges, but does not commit, and it stops to wait for the conflict to be resolved. To see which files conflict when merging, you can use thegit statusconsult

$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:      index.html

no changes added to commit (use "git add" and/or "git commit -a")

Any files that contain unresolved conflicts are listed as unmerged. Git will add standard conflict resolution tags to the conflict files, which can be used to manually locate and resolve these conflicts. You can see that this file contains sections like the following:

<<<<<<< HEAD
<div id="footer">contact : [email protected]</div>
<div id="footer">
  please contact us at [email protected]
>>>>>>> iss53

After resolving all conflicts in all files, rungit addThe command marks them as resolved (essentially saving a snapshot to the staging area). Because once temporary, it means that the conflict has been resolved

Run it againgit statusTo confirm that all conflicts have been resolved

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   index.html

If you confirm that all conflicts have been resolved, you can use thegit commitTo complete this merge submission. Submission instructions are generated automatically

Merge branch 'iss53'

# It looks like you may be committing a merge.
# If this is not correct, please remove the file
#       .git/MERGE_HEAD
# and try again.

View branches

git branchIf the command does not add any parameters, it will give a list of all the current branches. Before the master branch*The character represents the current branch. In other words, if you submit the update now, the master branch will move forward with the development progress

$ git branch
* master

To view information about the last submitted object in each branch, rungit branch -v

$ git branch -v
  iss53   93b412c fix javascript issue
* master  7a98805 Merge branch 'iss53'
  testing 782fd34 add scott to the author list in the readmes

Delete branch

The previous work results have been merged into the master, so the iss53 branch is useless. have access togit branch -dCommand to delete it

$ git branch -d iss53

If a branch has not been merged, the branch needs to use-DOption to delete

$ git branch -D iss53

Git remote warehouse and branch

To participate in any git project collaboration, you must understand how to manage the remote warehouse. Remote warehouse refers to the project warehouse hosted on the network. When cooperating with others to develop a project, we need to manage these remote warehouses in order to push or pull data and share their work progress. Manage the work of remote warehouse, including adding remote library, removing remote library, managing remote library branches, defining whether to track these branches, etc

Remote branch is the index of the branches in the remote warehouse. They are local branches that cannot be moved; they are updated only when git interacts with the network. Remote branches are like bookmarks, reminding you of the location of the branches above when you last connected to the remote warehouse

A remote branch is usually represented in the form of (remote warehouse name) / (branch name), such asorigin/masterbranch

Clone remote warehouse

The command format of clone repository isgit clone [url]. For example, to clone the code repository GIT_ Learn, you can use the following command:

$ git clone [email protected]:littlematch0123/git_learn.git

This creates a new directory namedgit_learnThe. Git directory is used to save all the downloaded version records, and then take out the latest version of the file copy. If you enter this newgit_learnDirectory, you will see that all the files in the project are in it, ready for subsequent development and use. If you want to define the new project directory name when cloning, you can specify a new name at the end of the above command

$ git clone [email protected]:littlematch0123/git_learn.git learnGit

If the last character is a dot, it means that all the files of the project will be stored in the current directory, but the current directory should be empty at the beginning

$ git clone [email protected]:littlematch0123/git_learn.git .

View remote warehouse

To view which remote warehouses are currently configured, you can use thegit remoteCommand, which lists the short name of each remote library. After cloning a project, you can see at least one project namedoriginGit uses this name by default to identify the cloned original repository

$ git remote

You can also add the – V option (V is the abbreviation of — verb, which means lengthy in Chinese) to display the corresponding clone address. If you do not have push permission, you will not see the push address

$ git remote -v
origin    [email protected]:littlematch0123/git_learn.git (fetch)
origin    [email protected]:littlematch0123/git_learn.git (push)

Add remote warehouse

Usually, a local git warehouse corresponds to a remote warehouse; however, in some cases, a local warehouse needs to be associated with multiple remote warehouses at the same time, such as publishing a project on GitHub and coding at the same time

Add a new remote warehouse, you can specify a name for future reference, rungit remote add [shortname] [url]

$ git remote add coding [email protected]:ehuo0123/git_learn.git
$ git remote -v
coding    [email protected]:ehuo0123/git_learn.git (fetch)
coding    [email protected]:ehuo0123/git_learn.git (push)
origin    [email protected]:littlematch0123/git_learn.git (fetch)
origin    [email protected]:littlematch0123/git_learn.git (push)

Push local branch

git pushThe command is used to push the update of the local branch to the remote host

$git push < remote host name > < local branch name >: < remote branch name >

The following command means to take out my local serverfix branch and push it to the serverfix branch of the remote warehouse

$ git push origin serverfix:serverfix

Of course, branch names can be different, but this is not recommended

git push origin serverfix:awesomebranch

Because the names of local and remote branches are the same, the following is a brief description

$ git push origin serverfix

If you want to push the local master branch to the origin server, you can run the following command

$ git push origin master

The following command means to push the current branch to the corresponding branch of the origin host. If the current branch is a master branch, it will push the master branch. If it is an X branch, it will push the X branch

$ git push origin

Generally, if the current branch has only one tracing branch, the host name can be omitted

$ git push

If the current branch has a tracking relationship with multiple hosts, you can use the-uOption to specify a default host so that it can be used without any parametersgit push

$ git push -u origin master

No matter whether there is a corresponding remote branch or not, all local branches are pushed to the remote host–alloption

$ git push --all origin

Grab data from server

usegit fetchCommand grabs all branch data from the server

$ git fetch origin
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/littlematch0123/git_learn
 * [new branch]      y          -> origin/y

If the branch name is added, only the data of the branch is updated

$ git fetch origin master

But it’s important to note that,fetchThe command only grabs data and does not automatically generate an editable copy (copy) locally. In other words, in this case, there won’t be a new Y branch – just one origin / y pointer that can’t be modified

It worksgit merge origin/yMerge these jobs into the current master branch

$ git merge origin/y

If you want to work on your own Y branch, you can build it on the remote tracking branch

$ git checkout -b y origin/y

Checking out a local branch from a remote tracking branch automatically creates a so-called “tracking branch” (the branch it tracks is called an “upstream branch”). A tracking branch is a local branch that has a direct relationship with a remote branch. A tracking relationship is established between the local branch and the remote branch

When a repository is cloned, it usually automatically creates a traceorigin/masterMaster branch of

If you type on a trace branchgit pullGit can automatically identify which server to grab and which branch to merge. So, actually,git pullyesgit fetchHeelgit merge FETCH_HEADThe abbreviation for.

$git pull < remote host name > < remote branch name >: < local branch name >

For example, to retrieve the next branch of the origin host and merge it with the local master branch, you need to write the following

$ git pull origin next:master

If the remote branch (next) is to be merged with the current branch, as follows:

$ git pull origin next

If there is a tracing relationship between the current branch and the remote branch, GIT pull can omit the remote branch name

$ git pull origin

If the current branch has only one tracing branch, even the remote host name can be omitted

$ git pull

Ifgit pullPrompt whenno tracking information, which indicates that the tracking relationship between the local branch and the remote branch has not been createdgit branch --set-upstream branch-name origin/branch-nameTo establish the tracking

Delete remote branch

Omitting the local branch name means deleting the specified remote branch, because it is equivalent to pushing an empty local branch to the remote branch

The following command removes the X branch of the origin host

$ git push origin :x
#Equivalent to
$ git push origin --delete x

Remote warehouse delete and rename

$git remote rename coding CD # rename
$git remote RM coding # delete

Remote warehouse is not differentiated

Due to the addition of multiple remote warehouses, we are faced with the problem of warehouse selection when we push and pull. It is true that this is more rigorous, but in many cases, it is only necessary to keep the remote warehouse completely consistent, and there is no need to make a distinction, so such a distinction is somewhat “redundant”

Check the currentgit remotesituation

$ git remote -v
origin    [email protected]:littlematch0123/git_learn.git (fetch)
origin    [email protected]:littlematch0123/git_learn.git (push)

Next, instead of adding additional remote warehouses, add additional URLs to the existing remote warehouses

usegit remote set-url --add <name> <url>To add a remote address to an existing remote warehouse

$ git remote set-url --add origin [email protected]:ehuo0123/git_learn.git

View the associated remote warehouse again:

$ git remote -v
origin    [email protected]:littlematch0123/git_learn.git (fetch)
origin    [email protected]:littlematch0123/git_learn.git (push)
origin    [email protected]:ehuo0123/git_learn.git (push)

In this way, the set push and pull operations are exactly the same as the original operation, and there is no need to adjust them

If you no longer need multiple warehouses, you can usegit remote set-url --delete <name> <url>, delete it

$ git remote set-url --delete origin [email protected]:ehuo0123/git_learn.git

Git other operations

Delete file

1. Delete the file from the working directory and use it directlyrmCommand to delete, because it is not included in Git version library, GIT does not know

Touch a # new a
RM a # delete a

If you use it to add to the storygit rm aInstead, it will prompt an error

$ git rm a
fatal: pathspec 'a' did not match any files

2. To delete a file from the staging area, you need to use thegit rm -fCommand to force the deletion

Touch B New B
Git add B # add B to the staging area
Git RM - F B # delete B

If usedgit rm b, the following error will be prompted

$ git rm b
error: the following file has changes staged in the index:
(use --cached to keep the file, or -f to force removal)

3. Delete files from local warehouse, usegit rmJust order

Touch C # new C
Git add C # add C to the staging area
Git commit - M 'add C'
Git RM C # delete C

4. If you just want to delete the file from git repository (that is, remove it from the staging area), but still want to keep it in the current working directory. In other words, it’s just removed from the tracking list. For example, after some files are accidentally brought into the warehouse, you need to remove the trace without deleting the files, so that you can delete them later.gitignoreFill in the file with the — cached option

$ git rm d --cached

File rename

1. Rename a file from the working directory and use it directlymvCommand to delete, because it is not included in Git version library, GIT does not know

Touch a # new a
MV A A1 # rename a to A1

If you use it to add to the storygit mv a a1Instead, it will prompt an error

$ git mv a a1
fatal: not under version control, source=a, destination=a1

2. Rename a file from the staging area or local warehouse, and use it directlygit mvJust order

$ git mv b1 b2
localhost:t bailiang$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    b1 -> b2

Undo operation

At any time, you may need to undo some of the actions you just did. But we should pay attention to that some undo operations are irreversible, so we should be careful. Once we make mistakes, we may lose some of our work results

1. Modify last submission

Sometimes, after submission, it is found that several documents have not been added, or the submitted information is wrongly written. To undo the commit operation, you can use the--amendOption re submit:

$ git commit --amend

If you forget to save some changes when submitting, you can add the save operation first, and then run it--amendSubmit

$ git commit -m 'initial commit'
$ git add forgotten_file
$ git commit --amend

The above three commands result in only one submission, and the second one corrects the first one

2. Cancel staged files
usegit reset HEAD <file>...Command can cancel the temporary storage and restore the files in the temporary storage area to the working directory

$ git reset HEAD a.txt

3. Cancel modification of file

usegit checkout -- <file>...Command to restore the file to the previous version. It should be noted that this command is very dangerous, any changes to the file will disappear, because it just copies another file to cover it. Don’t use this command unless you really don’t want that file

$ git checkout -- a.txt

matters needing attention

1. Version control system can only track the changes of text files, such as txt files, web pages, all program codes and so on. Although these binary files, such as pictures and videos, can also be managed by the version control system, they can’t track the changes of the files. They can only string the binary files together every time they are changed, that is, they only know that the pictures are changed from 100kb to 120KB, but the version control system doesn’t know what they have changed

Microsoft Word format is binary format, so version control system can’t track word

Of course, there are ways to do it, and it needs to be installeddocx2txtProgram, the word document into a readable text file

Add the following line to the. Gitattributes file:

*.docx diff=word

Write a script to wrap the output in a git supported format. Create a file called docx2txt in the executable path and add these contents:

docx2txt.pl $1 -

usechmod a+xAdd executable permissions to this file. Finally, GIT needs to be configured to use the script

$ git config diff.word.textconv docx2txt

Now if you compare two snapshots, GIT will apply a “word” filter, docx2txt, to those files that end in. Docx. In this way, word files can be efficiently converted into text files and compared

2. Do not edit any text files with the notepad that comes with windows. The reason is that Microsoft’s Notepad development team used a very retarded behavior to save UTF-8 encoded files. They cleverly added the character of 0xefbbbf (hexadecimal) at the beginning of each file, and they would encounter many incredible problems

3、git commit -amIt can be written asgit commit -a -mBut it can’t be written asgit commit -m -a

4. In git, anything that has been submitted can almost always be recovered, but anything that has not been submitted will probably never be found after it is lost

Git common commands

Basic operation

$git init # initialize the warehouse
$git add < File >? Track new files, or put the tracked files in the temporary storage area
$git add. # batch track all untracked files in the working directory
$git RM < File >? Delete files from local warehouse
$git RM - f < File >? Delete files from the cache
$git RM -- cached < File >? Is deleted from git repository, but remains in the current working directory
$git commit # submit the file to the local warehouse
The $git commit - M 'write a file' # - M parameter is followed by the way of submission description, and the update is submitted in one line of command
$git commit - am 'write a file' #
$git commit - V # start the text editor to enter the description of this submission, and the editor will display the changes compared with the last submission
$git commit -- amend # modify last commit
$git reset head < File >? Cancel staging
$git checkout -- < File >? Restore file content

View actions

$git status # check the current file status
$git status - s # state output in a more compact format
$git diff # view differences between working directory and staging area
$git diff -- cached # view the difference between the staging area and a submission. The default is head
$git diff Id1 Id2 # view the difference between two submissions
$git log # view submission history
$git log - P # expand to display the content difference of each submission
$git log - 2 # displays only the last two updates
$git log -- oneline # each submission is displayed on one line
$git log -- all # displays the commit records of all branches
$git log -- graph # displays the branch merging history of ASCII graphic representation
$git reflog # is arranged in order according to all previous commit paths to record each command

Branch operation

$git branch # lists all branches, and the current branch is preceded by a * sign
$git branch - V # view the information of the last submitted object of each branch
$git branch < branchname >? New branch
$git branch - d < branchname >? Delete branch
$git branch - d < branchname > #, which is used to delete branches that have not been merged
$git checkout < branchname >? Branch switching
$git checkout - B < branchname >? Create a new branch and switch to it
$git checkout - # move head to the previous branch
$git merge < branchname >? Merge the target branch into the current branch
$git reset -- hard < commit > # rollback the current branch to a historical version, and the submitted content will be copied to the staging area and working directory

Remote operation

$git remote # view all remote warehouses
$git remote - V # displays the clone address corresponding to the remote warehouse
$git remote add [shortname] [url] #
$git remote rename Pb Paul # change the name of the remote library from Pb to Paul
$git remote RM [shortname] # disassociates the remote library
$git remote set URL -- add < name > < URL >? Add additional URL to the existing remote warehouse
$git remote set URL -- delete < name > < URL >? Delete additional URLs for existing remote warehouses
$git clone < address >? Clone all branches of the remote warehouse
$git push origin < branchname >? Take out the local < branchname > branch and push it to the remote warehouse's < branchname > branch
$git fetch origin # grabs all branch data from the remote server
$git pull origin < branchname >? Is equivalent to the combination of fetch and merge commands
$git push origin: serverfix # delete the serverfix branch on the server
$git push origin -- delete serverfix # another way to delete a server branch

Recommended Today

Rust and python: why rust can replace Python

In this guide, we compare the rust and python programming languages. We will discuss the applicable use cases in each case, review the advantages and disadvantages of using rust and python, and explain why rust might replace python. I will introduce the following: What is rust? What is Python? When to use rust When to […]