I. Version control summary

1.1 What is version control

Revision Control (Revision Control) is a software engineering technique used to manage the history of changes we have made to a file, directory, or project during development. It is easy to view the history of changes and back up to restore the previous version.

  • Achieve cross-regional multi-person collaborative development
  • To track and record the history of one or more files
  • Organize and protect your source code and documentation
  • Statistical workload
  • Parallel development, improve development efficiency
  • Track and record the entire software development process
  • Reduces the burden on developers, saves time, and reduces human error

Simply put, it is a technology for managing collaborative development projects.

No version control or lack of the right process management, version control itself can introduce a lot of problems in the software development process, such as the consistency of software code, software redundancy, software process the content of the sex, the concurrency in the process of software development, the security of software source code, and software integration, etc.

1.2 Common Terms

1. The Workspace tree (Workspace) is the folder where the programmer makes development (changes).

Staging areas are used by workspaces to Staging changes before they commit them.

Git directory index file, the staging area will record git add file information (file name, size, timestamp…) , does not save the file entities, and points to each file entity by id.

You can use Git Status to check the state of the staging area!

3. Local Repository

After git commit, you can synchronize the index directory tree to the local repository, which is convenient for you to synchronize the local repository and remote repository through Git push.

Note 1: Only after the modification is committed to the local repository, the modification can leave traces in the repository. Note 2: You can create a local repository anywhere. You only need to run git init command in the target directory to automatically initialize this directory as a local repository, and it will create a “.git” directory

Content may be modified by collaborating local repositories in multiple locations, so it may or may not be in sync with the local Repository.

An Index is another term for a staging area.

6. Check in to copy the new version back to the repository.

7. Check out copies the latest revisions of files from the repository to the workspace.

Make changes to working copies of the respective files and Commit those changes to the repository.

9. Conflict: Multiple people making changes to a working copy of the same file and committing those changes to a repository.

Merge to join changes on a branch to this trunk or another branch with the main trunk.

Branch a separate copy of the main line. The default Branch is called master.

Obtain exclusive permission to modify files.

The HEAD is a symbolic reference, most commonly used to point to the currently selected branch.

14. Revision represents the status of a version of the code. Git identifies different versions by their ids, which are represented by the SHA-1 hash algorithm.

Tags refer to the state of a branch at a particular point in time. With the tag, you can easily switch to the state at the time of the tag.

1.3 Common Version Controllers

Mainstream version controllers include the following:

  • Git
  • SVN (Subversion)
  • CVS (Concurrent Versions System)
  • VSS (Microsoft Visual SourceSafe)
  • TFS (Team Foundation Server)
  • Visual Studio Online

Version Control products are numerous (Perforce, Rational ClearCase, RCS (GNU Revision Control System), Serena) Dimention, SVK, BitKeeper, Monotone, Bazaar, Mercurial, SourceGear Vault), now the most influential and widely used ones are Git and SVN.

1.4 Classification of version control

1.4.1 Local version control

Record each update of the file, which can be a snapshot of each version, or record patch files for personal use, such as RCS.

1.4.2 Centralized version control

All version data is stored on the server, and developers can synchronize updates or upload their own changes from the server.

All version data is stored on the server, and the user only has the previously synchronized version locally. If the user is not connected to the network, the user cannot see the historical version, switch version verification issues, or work in different branches. Also, with all the data kept on a single server, there is a significant risk that the server will break down and all the data will be lost, which of course can be backed up regularly. Products: SVN, CVS, and VSS.

1.4.3 Distributed version control

All version information repositories are synchronized to each user locally, so that all version history can be viewed locally, and can be submitted locally offline, just push to the corresponding server or other users when networking. Since each user stores all version data, it takes only one user’s device to recover all data, but this increases the use of local storage space.

1.5 Main Differences between Git and SVN

The SVN is a centralized version control system, and the version library is centrally located on the central server. When working, you use your own computer. Therefore, you need to get the latest version from the central server first. The centralized version control system must be connected to the network to work, which requires a high network bandwidth.

Git is a distributed version control system. There is no central server. Everyone’s computer is a complete version library. For example, if you change file A on your computer and someone else changes file A on your computer, you only need to push your changes to each other, and then you can see each other’s changes.

Install and configure Git

2.1 What is Git

Git is the most advanced distributed version control system in the world.

Git is free and open source.

Git was originally developed to assist the Linux kernel as an alternative to BitKeeper.

Linus Torvalds, 1969, Finland.

Advantages:

  • Suitable for distributed development with emphasis on individuals
  • Public server pressure and data volume are not too large
  • Fast and flexible
  • Conflicts can be easily resolved between any two developers
  • Support offline work

Disadvantages:

  • Mode is more complex than SVN
  • Out of the box
  • Code confidentiality is poor, and once the developer has cloned the entire library, all code and version information can be fully disclosed

Liverpoolfc.tv: git-scm.com/

Source: github.com/git/git/

2.2 Setting up Git working environment

2.2.1 download Git

Open the Git official website and download the version of the git operating system

Select version:

Here I chose to download 64-bit Git for Windows Setup

2.2.2 install Git

Select the installation configuration information

Keep Next by default, and read the options on the installation screen carefully if you need to set them

Then start the Git

After the installation is successful, there will be Git item in the Start menu, and there are 3 programs under the menu:

Git Bash: Unix and Linux style command line, most used, most recommended

Unlike doS-style commands, you can choose Git CMD

Git CMD: A Windows-based command line

Git GUI: It is not recommended for beginners to use Git. Try to get familiar with common commands first

Click Create New Repository to directly Create a New Repository.

2.2.4 Installing Git on Linux and Mac OS

Git: sudo apt-get install Git

Git: git-scm.com/download/ma… .pkg installation

2.2.5 Bash Basic operation commands

  1. CD: Change the directory
  2. CD.. : Returns to the previous directory and goes to the default directory
  3. PWD: Displays the current directory path
  4. Ls (ll) : both list all files in the current directory, but ll(two ll) lists in more detail
  5. Touch: Create a new file such as touch index.js will create an index.js file in the current directory
  6. Rm: If you delete a file, rm index.js deletes the index.js file
  7. Mkdir: Create a directory, that is, create a folder
  8. Rm -r: deletes a folder. Rm -r SRC Deletes the SRC directory. It seems that wildcards cannot be used
  9. Mv: move the file, mv index.html SRC index.html is the file we want to move, SRC is the target folder, of course, to write this, you must make sure that the file and the target folder are in the same directory
  10. Reset: reinitialize the terminal or clear the screen
  11. The clear: clear screen
  12. History: Displays the command history
  13. Help, help
  14. Exit, exit
  15. # : indicates a comment

2.3 the Git configurationgit config

2.3.1 Viewing the Configurationgit config -l

Use git config -l to see the current git environment configuration in detail

View different levels of configuration files:

Check the system configuration information
$ git config --system --list

# View current user (global) configuration information
$ git config --global --list

Check the current repository (local) configuration
$ git config --local --list
Copy the code

2.3.2 Classification of Git configuration files

On Windows, Git looks for the.gitconfig file in the HOME directory (usually under C:\Documents and Settings\USER).

There are three Git configuration files:

  1. /etc/gitconfig: contains values applicable to all users and all projects in the system (Win: C:\Program Files\Git\mingw64\etc\gitconfig) –system system level

  1. ~/.gitconfig: applies only to the configuration of the current login user. (Win: C:\Users\ administrator.gitConfig) –global

  1. .git/config in the Git project directory: the configuration that applies to a particular Git project. (Win: C:\gitProject) –local Current project

Note: For the same configuration item, the priority of the three profiles is 1<2<3

You can edit the configuration file directly. The configuration file will respond to the configuration file after you run a command.

2.3.3 Setting the User Name and Email Address

The first thing to do when you install Git is to set up your username and E-mail address. This is very important because this information is used with every Git commit and is permanently embedded in your commit:

$ git config --global user.name "w"  	       # the name
$ git config --global user.email ***@qq.com    # mailbox
Copy the code

You only need to do this once, if you pass the –global option, because Git will always use that information to handle everything you do in the system. If you want to use a different name or E-mail address for a particular project, you can run this command in that project without the –global option.

Overall –global is a global configuration, not a project-specific configuration.

2.3.4 Adding or Deleting configuration items

1) Add configuration items

$ git config [--local|--global|--system]  section.key value
[--local|--global|--system]  Optional for local, global, and system Settings. See 2.3.2
section.key 				 Key under the # area
value 						 The value corresponding to #
Copy the code
  • – the local project level
  • — Global Current user level
  • – the system the system level

For example, if we want to add a profile with a height of 198 under the student area, the result is as follows:

2) Delete configuration items

$ git config [--local|--global|--system] --unset section.key
Copy the code

Remove the system-level height configuration

2.3.5 More Configuration items

$ git config --global color.ui true     Turn on all default terminal coloring
$ git config --global alias.ci commit   The # alias ci is the alias for commit
[alias]  
co = checkout  
ci = commit  
st = status  
pl = pull  
ps = push  
dt = difftool  
l = log --stat  
cp = cherry-pick  
ca = commit -a  
b = branch 

user.name  # username
user.email  # mailbox
core.editor  # Text editor
merge.tool  # Difference analysis tool
core.paper "less -N"  # Configure the display mode
color.diff true  #diff Color configuration
alias.co checkout  # Set alias
$ git config user.name  # Get user name
$ git config core.filemode false  Ignore files whose permissions are modified
Copy the code

2.3.6 *config Command parameters

Git config [<options>] config file location --global# Use global config file
    --system                  # Use system config file
    --local                   # Use repository config file
    -f, --file <file>         # Use given config file
    --blob <blob-id>          # Read Config from given blob Object Read configuration from given blob objectAction --get#get value: name [value-regex] get value: name [value-regex]
    --get-all                 #get all values: key [value-regex] get all values: key [value-regex]
    --get-regexp              #get values for regexp: name-regex [value-regex
    --get-urlmatch            #get value specific for the URL: section[.var
    --replace-all             # Replace all matching variables: Name value [value_regex]
    --add                     #add a new variable: name value
    --unset                   #remove a variable: name [value-regex] Remove a variable name [value] : regular expression
    --unset-all               #remove all matches: name [value] #remove all matches: name [value]
    --rename-section          #rename section: old-name new-name
    --remove-section          #remove a section: name
    -l, --list                #list all
    -e, --edit                # Open an Editor
    --get-color               #find the color configured: slot [default]
    --get-colorbool           #find the color setting: slot [stdout is tty]Type --bool#value is "true" or "false"
    --int                     #value is decimal number
    --bool-or-int             #value is --bool or --int
    --path                    #value is a path (file or directory name)Other -z, --null# Terminate values with NUL byte
    --name-only               #show variable names only Displays only variable names
    --includes                # Respect include Directives on lookup
    --show-origin             #show origin of config (file, standard input, blob, command line
Copy the code

Iii. Git Theoretical basis

3.1 Work Area

Git local has three work areas:

Working Directory, Stage/Index, Repository (or Git Directory), and Remote Git Directory can be divided into four work areas. The conversion relationship between the four areas is as follows:

  • Workspace: The Workspace is where you normally store your project code
  • Index/Stage: the staging area, used to temporarily store your changes, which is actually just a file that holds the information to be submitted to the list of files
  • Repository: a warehouse area (or local Repository) where data is safely stored and where you commit data to all versions. Where HEAD points to the latest version put into the repository
  • Remote: A server that hosts code, which can simply be thought of as one of your project’s computers for Remote data exchange

The three local areas are exactly the versions that the HEAD points to in the Git repository!

  • Directory: a Directory managed using Git, that is, a repository containing our workspace and Git’s admin space. .git + Workspace)
  • Workspace: The directories and files that make up the Workspace that need to be versioned through Git.
  • Git: directory for storing Git management information. It is automatically created when the repository is initialized.
  • Index/Stage: the staging area, or pending update area, where we can put all updates before committing to the Repo.
  • Local Repo: Local repository, a repository that is stored locally; HEAD is just the current development branch.
  • Stash: Stash is a stack of working states used to save/restore temporary states in the Workspace.

3.2 Workflow

Git’s workflow generally looks like this:

  1. Add and modify files in the working directory.

  2. Put the files that need to be versioned into the staging area;

  3. Commit files from the staging area to the Git repository.

Thus, files managed by Git have three states: modified, staged, and Committed

3.3 Graphical Tutorial

I think Git is more complicated than other version controllers. Here is a tutorial:

Illustrated tutorial English original edition

Illustrated Tutorial Chinese version

4. Git operation

4.1 Creating a Working Directory and Common Instructions

The Workspace directory is usually the folder you want Git to help you manage. It can be the directory of your project or an empty directory.

For daily use, just remember the following six commands:

4.2 Getting Git Repositories

There are two ways to create a local repository: one is to create an entirely new repository (Git init), the other is to clone a remote repository (Git Clone).

4.2.1 Creating a New Warehouse

You need to use the root directory of your GIT managed project to execute:

Create a New Git repository in the current directory
$ git init
Copy the code

Perform:

After executing, you can see that there is only one more.git directory in the project directory, where all the information about versions and so on is stored.

Of course, you can do this with the repository if you use the following command:

Create a new directory and initialize it as a Git code base
$ git init [project-name]
Copy the code

Perform:

4.2.2 Cloning a remote Repository

Clone (clone) : Clone (clone) : clone (clone) : clone (clone) : clone (clone) : clone (clone) : clone (clone) : clone (clone) : clone (clone)

# Clone a project and its entire code history (version information)
$ git clone [url]
Copy the code

Perform:

Let’s say we’re hosting on GitHub from a cloned remote repository:

Results:

4.3 Git File operation

Version control refers to the version control of a file. To modify or commit a file, you must first know the current state of the file. Otherwise, you may commit a file that you don’t want to commit, or the file that you want to commit may not be committed. GIT does not care about the specific differences between the two versions of the file, but is concerned about whether the file as a whole has changed. If the file is changed, a snapshot of the new version of the file is generated when the commit is added. The method to determine whether the file as a whole has changed is to calculate the checksum of the file using the SHA-1 algorithm.

4.3.1 Four File States

  • Untracked:Untracked, this file is in a folder, but is not added to the Git repository and does not participate in version control. throughgit addState changes toStaged .
  • Unmodified: The file is stored in the repository but is not modified. That is, the file snapshot content in the repository is the same as that in the folder. This type of file has two places to go, if it is modified, toModified. If usedgit rmTo transfer the publishing library toUntrackedFile.
  • Modified:The file has been modified, just modified, nothing else has been done. This file also has two places to go throughgit addCan enter temporary storagestagedStatus, usegit checkoutDiscard the modifications and return toUnmodifiedState, thisgit checkoutThat is, to overwrite the current changes by fetching the file from the library.
  • Staged:Temporary state. Executegit commitThen the changes are synchronized to the library, and the file in the library and the local file become the same again, and the file isUnmodify Status. Executiongit reset HEAD filenameUnsave, the file status isModified .

4.3.2 Viewing the File Status (status)

You can view the status of a file by running the following command:

Check the status of the specified file
$ git status [filename]

Check the status of all files
$ git status
Copy the code

Perform:

Results:

The status of the foo.htm file is untracked, suggesting that it can be saved via Git add.

GIT does a good job of this by printing out the state of each file along with instructions on how to do it. There are instructions on how to stage-save, how to track files, and how to unstage-save: use “GIT add…” to include in what will be committed.

4.3.3 Adding Files and Directories (add)

A Working Directory is a Directory that you can see on your computer.

A Repository workspace has a hidden directory. Git, which is not a workspace, but a Repository for Git.

Git’s repository contains many things. The most important is a staging area called stage (or index), the first branch that Git automatically creates for us, the master, and a pointer to the master called HEAD.

Add a file with untracked state to the temporary area with the syntax as follows:

# Add the specified file to the staging area
$ git add [file1] [file2] ...

# Add the specified directory to the staging area, including subdirectories
$ git add [dir]

Add all files from the current directory to the staging area
$ git add .
Copy the code

Perform:

4.3.4 Removing Files and Directories (Undo add)

When the following command is executed, files are directly deleted from the staging area and the workspace is not changed:

Delete files directly from the staging area, leaving the workspace unchanged
$ git rm --cached <file>
Copy the code

Execute command:

Remove the add file by overwriting the directory tree:

If the file has been added to the stage using the add command, it needs to be removed from the stage first
$ git reset HEAD <file>...
Copy the code

When the git reset HEAD command is executed, the tree of the stage is overwritten and replaced by the tree of the master branch, but the workspace is not affected.

Execute: withdraw the F1.txt file from the staging area to the workspace

Remove all untracked files:

# Remove all untracked files
-d indicates the included directory, and -f indicates the mandatory cleanup.
$ git clean [options] 
Copy the code

Perform:

Remove front:

Perform removal:

Removed:

Rm, mv

# Remove only from the stage, keep the physical files!
$ git rm --cached readme.txt 

# Delete not only from stage, but also physical files!
$ git rm readme.txt 

# rename a.t_t to B.t_t
$ git mv a.txt b.txt 
Copy the code

4.3.4 conclusion:

  1. When a Git commit is performed, the staging tree is written to the repository, and the master branch is updated accordingly. That is, the directory tree that the master points to is the staging tree at the time of commit.

  2. When you performgit reset HEADCommand, the staging area directory tree is overridden and replaced by the one the master branch points to, but the workspace is not affected.

  3. When the git rm -cached

    command is executed, the file is directly removed from the staging area, leaving the workspace unchanged.

  4. When the git checkout or git checkout –

    command is executed, the files in the workspace are replaced with all or specified files in the staging area. This operation is dangerous and will clear the changes in the workspace that have not been added to the temporary.

  5. When the git checkout HEAD or git checkout HEAD

    command is executed, the staging area and the files in the workspace are replaced with all or part of the files in the master branch pointed to by the HEAD! This command is also extremely dangerous because it will clear uncommitted changes not only in the workspace, but also in the staging area.

4.3.5 Viewing The Difference After The Modification (diff)

Git diff is used to show the difference between files in the Workspace and files in the staging area

Git status = git status = git status = git status = Git status

# Check the difference after file modification
$ git diff [files]
Copy the code

Perform:

—a indicates the original file, and +++b indicates the new file

Compare files in the staging area with files that have already been committed
$ git diff --cached
Copy the code

You can also diff the Workspace state and the repo state by running the following command:

Compare the repo to the files in the workspace
$ git diff HEAD~n
Copy the code

4.3.6 Checkout

If the file f4.txt already exists in the repository, you can use checkout to checkout the overwrite if you want to undo it

The git checkout command, one of the most common git commands, is also a dangerous one because it overwrites the workspace.

Grammar:

# use a
$ git checkout [-q] [<commit>] [--] <paths>...
Use # 2
$ git checkout [<branch>]
The usage of # 3
$ git checkout [-m] [[-b]--orphan] <new_branch>] [<start_point>]
Copy the code

Is optional, if omitted, it is equivalent to checking out from the staging area (index).

# Check out branch. To complete the three steps in the figure, update the HEAD to point to the branch branch, and update the staging area and workspace with the tree that the branch points to.
$ git checkout branch

# Summary shows the differences between workspace, staging area and HEAD.
$ git checkout

# same as above
$ git checkout HEAD

Overwrite filename in the workspace with filename in the staging area. This is equivalent to canceling local changes made since the last time git add filename was executed (if any).
$ git checkout -- filename

# Keep HEAD pointing the same. Replace the corresponding file in the staging area and workspace with the filename in the commit pointed to by branch. Note that the filename file in the staging area and workspace will be overwritten directly.
$ git checkout branch -- filename

Note that the git checkout command is followed by a dot (". ). This is the most dangerous order! Cancellations all local changes (relative to the staging area).
# Equivalent to using all files in the temporary area directly overwrite the local file, without giving the user any chance to confirm!$git checkout --. Or $git checkout.Git checkout -- file_name restores the file to its current state in the local repository if no commit_id is used.
$ git checkout commit_id -- file_name
Copy the code

Example:

4.3.6 Ignoring files (.gitignore)

There are certain files that we don’t want to put under version control, such as database files, temporary files, design files, etc

Create a.gitignore file in your home directory. This file has the following rules:

  1. Ignoring blank lines in the file or lines that start with a pound sign (#) are ignored
  2. Linux wildcards can be used. For example, the asterisk (*) represents any number of characters, and the question mark (?) Represents a single character, square brackets ([ABC]) represents a range of optional characters, curly braces ({string1,string2… }) represents an optional string, etc
  3. If the name is preceded by an exclamation point (!) Is an exception rule that is not ignored
  4. If the name is preceded by a path separator (/), the file to be ignored is in this directory, while files in subdirectories are not ignored
  5. If the name is followed by a path separator (/), it means that subdirectories of the name in the directory are to be ignored, not files (default: both files and directories are ignored).
# for comments
*.txt 		Ignore all files ending in.txt! lib.txtExcept the # lib. TXT
/temp 		Ignore only TODO files in the project root directory, excluding other directories temp
build/ 		Ignore all files in the build/ directory
doc/*.txt 	# ignore doc/notes.txt but not doc/server/arch.txt
Copy the code

Example: Create a.gitignore file that ignores all log files

Check status:

From the figure above you can see that the two log files are not added to the staging area and are simply ignored.

Git ignored files for various languages and projects: github.com/github/giti…

Example: the generic java.gitignore file

# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
Copy the code

For more rules, click here

4.3.7 Commit (Commit)

With ADD, you simply add a file or directory to the index staging area. With COMMIT, you can commit a staging area file to a local repository.

Submit the temporary storage area to the warehouse district
$ git commit -m [message]

# Submit the files specified in the staging area to the warehouse district
$ git commit [file1] [file2] ... -m [message]

# Commit workspace change since last commit, go directly to warehouse area, skip add, invalid for new file!!
$ git commit -a

All diff information is displayed on submission
$ git commit -v

Use a new commit instead of the previous commit
# Overwrite the commit information from the previous commit if nothing new has changed
$ git commit --amend -m [message]

Redo the previous commit, including new changes to the specified files
$ git commit --amend [file1] [file2] ...
Copy the code

Example:

Status before submission

submit

Status after submission:

As you can see from the figure above, bar.htm is missing from the staging area

Revision to submit

If you find that a file has been changed, or if you just want to change the commit instructions, you can modify the file, add the modified file to the staging area via git add, and then run the following command:

# Revision submission
$ git commit --amend
Copy the code

Undo the commit

The idea is to discard the workspace and index changes, with the HEAD pointer pointing to the previous commit object

# Undo the last commit
$ git reset --hard HEAD~1
Copy the code

To view the commit log through Git log, you can also specify the commit number or sequence number directly

Example:

Undo a commit: Git revert

This command rolls back all changes made to the specified commit and generates a new commit.

4.3.8 Logs and History (log)

The git log command is used to view the commit log.

# View the commit log
$ git log[<options>] [<revision range>] [[\--] <path>...]Copy the code

Example:

Git log — Graph shows the commit history relationship graphically, which makes it easy to view the branch information of the commit history, drawn by characters on the console.

Git log-1 shows 1 line.

Use history to see what commands you have entered under bash:

View all branch logs

Git reflog keeps a record of all updates for all branches in the repository, including those that have been revoked.

4.3.9 Viewing the File List

Use the git ls-files command to view a list of files in the specified state in the following format:

# View files in the specified state
$ git ls-files [-z] [-t] [-v] (--[cached|deleted|others|ignored|stage|unmerged|killed|modified])* (-[c|d|o|i|s|u|k|m])*
Copy the code

Example:

4.3.10 Undo Update (reset)

1. Undo the staging area update

Use Git Add to commit updates to the staging area. Git reset HEAD

… Move the staging area update out of the Workspace.

Example: F6 committed, Workspace modified, staging modified, undo

2. Undo the local repository update

Use Git Log to view the commit log

There are two ways to undo a commit: using the HEAD pointer and using commit-id

In Git, there is a HEAD pointer to the latest commit in the current branch. If we use HEAD^ for the current version, we can use HEAD^^ for the previous version. If we want to go back to an earlier commit, we can use HEAD~n (HEAD^ = HEAD-1, HEAD^^ = HEAD-2).

$ git reset --hard HEAD^
$ git reset --hard HEAD~1
$ git reset --59cf9334cf957535cb328f22a1579b84db0911e5
Copy the code

Example: Roll back to Add F6

Back before:

Back to back:

If you want to restore a withdrawn commit, you can use Git reflog to view all updates for all branches in the repository, including those that have been withdrawn.

$ git reset --hard HEAD@{7}s
$ git reset --hard e0e79d7
Copy the code

–hard: Undo and delete the corresponding update

–soft: Undo the corresponding updates and put the updated content into the Stage

4.3.11 Deleting a File

1. Delete untracked files

If the file is still untracked, you can simply delete the file, as shown in the following example:

2. Delete the submitted files

-f: forcibly deletes files in the workspace and staging area

Undo deletion:

# to discard changes in working directory
$ git checkout -- <file>...
Copy the code

3. Delete files in the staging area, but do not delete files in the working area

Git reset HEAD

… You can do the same

4.3.12 File Operation Summary

Git is powerful and flexible, there’s no doubt about it, but that’s what makes it so complex.

4.4 the Git branch

Branching is relatively difficult in Git.

Branching is a parallel universe in a science fiction movie, where while you are trying to learn Git at your computer, the other you are trying to learn SVN in another parallel universe.

If two universes don’t interfere with each other, it doesn’t matter who you are now. At some point, however, the two parallel universes merged, and you ended up learning both Git and SVN!

What do branches do in practice? Let’s say you’re trying to develop a new feature that will take two weeks to complete, and you write 50% of the code in the first week. If you commit it immediately, because the code hasn’t been written yet, the incomplete code base will cause people to stop working on it. If you wait until all the code has been written and then commit all at once, you run a huge risk of losing your daily progress.

Now that we have branches, we don’t have to be afraid. You create a branch of your own, no one else can see, continue to work on the original branch, and you work on your own branch, commit as much as you want, until the development is finished, and then merge on the original branch, so that it is safe, and do not affect the work of others.

Git branches are very fast.

As of now, there is only one timeline, and in Git this branch is called the master branch. HEAD technically doesn’t point to commit, it points to master, and master points to commit, so HEAD points to the current branch.

Git branch

List all local branches
$ git branch

List all remote branches
$ git branch -r

List all local and remote branches
$ git branch -a

# Create a new branch, but stay in the current branch
$ git branch [branch-name]

Switch to the specified branch and update the workspace
$ git checkout [branch-name]

Switch to the previous branch
$ git checkout -

Create a new branch and switch to that branch
$ git checkout -b [branch]

# * create a branch that points to commit
$ git branch [branch] [commit-ish]

# Delete branch
$ git branch -d [branch-name]
# The branch 'feature-a' is not fully mergerd.
# If you are sure you want to delete it, run 'git branch -D feature-a'.
$ git branch -D [branch-name]

Delete remote branch (the following two commands are slightly different)
$ git push origin :master					$git push = $git push
$ git push origin --delete [branch-name]	Delete the remote repository branch when deleting the local repository branch record (physical delete)
$ git branch -dr [remote/branch]			Git /refs/remotes/

Create a new branch and set up a tracing relationship with the specified remote branch! (Is the new branch at the same time tracking!)
$ git branch --track [branch] [remote-branch]

Set up a tracing relationship between an existing branch and the specified remote branch! (It's an existing branch!)
# fatal: the '--set-upstream' option is no longer supported. 
# Please use '--track' or '--set-upstream-to' instead.
$ git branch --set-upstream [branch] [remote-branch]	# out of date!
$ git branch --set-upstream-to [remote-branch] [branch] # active!

Merge the specified branch into the current branch
$ git merge [branch]

# * Select a commit and merge into the current branch$git cherry-pick [<options>] [commit-ish] Optional options: --quit Quit the current chery-pick sequence --continueContinue with the current Chery-pick sequence -- ABORT cancles the current Chery-pick sequence and resumes the current branch -n, --no-commit No automatic commit! -e, --edit Edits the submitted informationCopy the code

Note:

  1. If you are planning on basing your work on an upstream hint: branch that already exists at the remote, you may need to run git fetch to retrieve it.

    • git fetchUpdate the local remotes folder with the GitHub repository instead of the head folder (** for example:When the remote repository creates a branch, usegit fetchcanEnables a local warehouse to retrieve a remote new branch, otherwise unknown!)
      • .git/refs/head/ : [local branch]
    • .git/refs/remotes/ : [branch being tracked]
    • Bottom line: Changes to the remote trace branch can only be made using git fetch or git push as a side-effect. We cannot operate on the remote trace branch directly, we must first switch back to the local branch and create a new COMMIT.
  2. Git is a distributed repository. Every Git repository is independent of each other. By default, there is no notification mechanism. This avoids the same stigma of having to connect to the Internet as SVN/CVS. After Git Clone, everyone gets a complete copy of the repository, so if the central repository goes down, just pick up someone else’s repository and restore it.

4.4.1 Creating and Switching branches

The default branch looks like this. Master is the main branch

$git branch [branch-name] $git branch [branch-name]

Switch branch to DEV1

Liao Xuefeng explained the branch more clearly, quote.

When you create a branch, such as dev, Git creates a pointer called dev that points to the same commit as master, and then points HEAD to dev to indicate that the branch is on dev.

Git creates a branch quickly because nothing changes in the workspace except adding a dev pointer and changing the HEAD point!

However, from now on, changes and commits to the workspace are made to the dev branch. For example, after a new commit, the dev pointer moves forward one step, while the master pointer remains unchanged.

If our work on dev is done, we can merge dev into master. How to merge Git? The easiest way to do this is to simply point master to dev’s current commit, and the merge is complete.

So Git merges branches fast! Change the pointer, the workspace content also unchanged!

After merging the branches, you can even delete the dev branch. Deleting the dev branch is deleting the dev pointer, and after deleting it, we are left with a master branch.

Git branch

(git branch

)

Switch to the previous branch

$git checkout -b [branch] $git checkout -b [branch]

$git branch [branch] [commit-ish] $git branch [branch] [commit-ish]

Select * from ‘dev3’ where ‘dev3’ = ‘master’ where ‘dev3’ = ‘master’;

There were two commits on master, so dev3 points to the first commit

$git branch –track [branch] [remote-branch] $git branch –track [branch] [remote-branch]

4.4.2 Viewing branches

1. List all local branches using $git Branch

2. List all remote branches using $git branch -r

3. Use $git branch -a to list all local and remote branches

4.4.3 Merge branches

$git merge [branch]

Merge branch = merge branch = merge branch = merge branch = merge branch = merge branch

The file11.txt main branch is now different from the dev6 content, as it was modified in Dev6 and can be viewed using the command:

Now we merge dev6 into the main branch, and you can see from the figure below that dev6 has one commit, but master does not

The content of the file11.txt file on the master is the same as that on the dev6 file, and the extra commits from dev6 are owned by the master.

4.4.4 Conflict resolution

If the same file is modified when merging branches, a conflict will occur as follows:

Submit the status of the first two branches:

In the dev6 branch, modify file11.txt:

The dev6 and master branch file11.txt files have been modified and committed, now merge the branches:

File11.txt in the master branch:

Git with < < < < < < <, = = = = > > > > > > > tag out the content of the different branches, the < < < HEAD is refers to the main branch modifications, > > > > > dev6 refers to dev6 on modifications.

After the conflict solution is that we can modify the file to resubmit, please pay attention to the current state of the master | done:

Conflict resolution after resubmission:

After resolving the conflict manually, you can add the file to the index and commit it with git commit, just as you would if you changed a file.

Git log –graph command to see the branch merge graph.

Branching strategy:

The master branch should be stable and be used to release new versions, so it should not be allowed to work on it. Work should normally be done on the new dev branch, and when the work is done, such as on the dev branch to release, or when the dev branch is stable, it can be merged into the master branch.

4.4.5 Deleting a Branch

To delete a local branch, run the $git branch -d [branch-name], -d (uppercase) command

To delete a remote branch, use the following command:

$ git push origin --delete [branch-name] 
$ git branch -dr [remote/branch]
Copy the code

-d: deletes a branch. The branch must be fully merged in its upstream branch, or upstream -r is not set on HEAD: indicates remotes, if -dr means to delete the remote branch.

4.5 Git GUI operations

Git GUI or IDE plug-in can make Git more intuitive. Common Git GUIs include the following:

4.5.1 making for the Desktop

The global developer dating club is a powerful tool with complete features and easy to use. GitHub is a handy tool for developers using GitHub.

GitHub for Desktop doesn’t come with a three-way merge tool, so you have to manually resolve conflicts yourself.

  • free
  • Support for both Windows and Mac: handy for developers who often need to switch between different operating systems
  • Beautiful Interface: As a tool for everyday staring, appearance level is very important
  • Support Pull Request: It is convenient to submit PR directly from the client
  • Timeline support: Displays the point in time and size of each submission directly on the Timeline
  • Support for Git LFS: Storing large files is more space efficient and efficient
  • Three-way merge is not supported: third-party tools are required

4.5.2 of the Source Tree

SourceTree is an old Git GUI management tool and claims to be the most useful Git GUI tool. Powerful, functional, basic and advanced operations are designed to be very smooth, suitable for beginners to get started, support Git Flow.

  • free
  • Powerful: Whether you’re a beginner or a heavy user, SourceTree makes you feel at home. For very heavy users, Source Tree also supports the execution of custom scripts.
  • Supports both Windows and Mac operating systems
  • Both Git and Mercurial VCS are supported
  • Built-in GitHub, BitBucket and Stash support: Directly bind accounts to operate remote Repos

4.5.3 Tortoise Git

Little turtle, the extensive use of SVN also makes this super easy to use THE SVN client has become almost every developer’s desktop must-have software. Small turtle only provide Windows version, provide Chinese version support.

  • free
  • Windows only: Good integration with file manager
  • Chinese interface
  • Operation experience inherits from Tortoise SVN

4.5.4 Git integrated GUI tool

Git installation is integrated with the INSTALLATION GUI tool, which can be found under the Git menu. It is free, simple, and does not require additional installation

4.6 Git Client integrated with the IDE

For programmers working with an IDE, having access to a source code management system without leaving the common IDE is the best option. Here are a few common IDE integrated Git clients:

4.6.1 Eclipse Egit

As a representative of the Java Integrated Development Environment, Eclipse has a built-in plug-in called Egit to provide git integration support. To be honest, the plugin is rich in functionality, from the normal Clone, Commit, pull/push operations to the more complex Git flow.

4.6.2 Visual Studio โ€“ Git Integration & GitHub Extension

Git support in VS is already pretty good. Clone repo directly on GitHub

4.6.3 IntelliJ IDEA

4.7 Help and Code Statistics

1. Help documents

After you have fully installed Git, there is an official help, which is the most authoritative source. The method is as follows:

For example, let’s look at the use of Git Commit

You can also search for git help online by going to the official website.

Address: git-scm.com/docs.

2. Information viewing and statistics commands

# Count the number of code submissions, including additions and delets:
$ git log --author="$(git config --get user.name)" --pretty=tformat: --numstat | gawk '{ add += $1 ; subs += $2 ; loc += $1 - $2 } END { printf "added lines: %s removed lines : %s total lines: %s\n",add,subs,loc }' -

# Warehouse submitters top 5 (if you look at all, remove the head pipe) :
$ git log --pretty='%aN' | sort | uniq -c | sort -k1 -n -r | head -n 5

# Warehouse Submitters top 5: This statistic may not be accurate as many people have different email addresses but use the same name
$ git log --pretty=format:%ae | gawk -- '{ ++c[$0]; } END { for(cc in c) printf "%5d %s\n",c[cc],cc; } ' | sort -u -n -r | head -n 5 

# Contributor statistics:
$ git log --pretty='%aN' | sort -u | wc -l

# Number of submissions:
$ git log --oneline | wc -l 

# Display files that have changed
$ git status

Display the version history of the current branch
$ git log

# Display the commit history and the files that changed each commit
$ git log --stat

# Search submission history, based on keywords
$ git log -S [keyword]

# Displays all changes after a commit, with each commit occupying one row
$ git log [tag] HEAD --pretty=format:%s

# Displays all changes after a commit, whose "commit notes" must match the search criteria
$ git log [tag] HEAD --grep feature

Displays the version history of a file, including file name changes
$ git log --follow [file]
$ git whatchanged [file]

Displays each diff associated with the specified file
$ git log -p [file]

# Show the last 5 submissions
$ git log -5 --pretty --oneline

# Display all submitted users, sorted by number of submissions
$ git shortlog -sn

Select * from user who modified the file and when
$ git blame [file]

Display the difference between the staging area and the working area
$ git diff

# Show the difference between the staging area and the previous commit
$ git diff --cached [file]

# Displays the difference between the workspace and the latest commit for the current branch
$ git diff HEAD

# Shows the difference between the two commits$ git diff [first-branch]... [second-branch]Displays how many lines of code you wrote today
$ git diff --shortstat "@{0 day ago}"

# Display metadata and content changes for a particular commit
$ git show [commit]

# Display files that have changed during a commit
$ git show --name-only [commit]

# Displays the contents of a file at the time of a commit
$ git show [commit]:[filename]

# Displays the most recent commits for the current branch
$ git reflog
Copy the code

Example:

5. Remote warehouse

Git is a distributed version control system, the same Git repository, can be distributed to different machines, but the development participants must be in the same network, and must have a original version of the project, the usual way is to have a computer as a server, 24 hours a day on. Everyone else would clone a copy of the “server” repository onto their computer and each would push their own submissions to the server repository and pull others’ submissions from the server repository. You could have built your own server to run Git, but for now it’s better to use a free hosting platform.

At the same time, compared to traditional code is managed to the local or Intranet. If there is a problem with the local or Intranet machine, code may be lost, and there will always be a backup using the remote repository. It also eliminates the hassle of building a native code versioning service. In the era of cloud computing, Git makes remote collaboration more convenient for developers with its powerful branch and cloning functions.

5.1 Hosting Platform

Git code hosting platform, first recommended is GitHub, many good open source projects from GitHub, but GitHub can only create public Git repositories, private repositories have to charge, sometimes access to comparison cards, if you are working on an open source project, GitHub is the first choice. Here are a few good Git code hosting platforms:

5.1.1 making

I’m sure you’ve all heard about GitHub, so I won’t go into details here.

5.1.2 GitLab

For some, GitHub naturally comes to mind with GitLab, which supports unlimited public and private projects. GitLab address: About.gitlab.com/

5.1.3 Bitbucket

Bitbucket is free to allow teams of five developers to create unlimited private code managed libraries

Bitbucket address: git.oschina.net/

5.1.4 Open source Chinese code hosting

Open Source China one account can create up to 1000 projects, including public and private, open source China code hosting addresses

5.1.5 coding.net

Talking about Coding.net (recommended), the first thing must be mentioned is that the speed is fast, the function is similar to open source China, the same account can create up to 1000 projects (5 private), also support the creation of tasks.

Coding.net address: coding.net/

I recommend Coding.net and GitHub for personal comparison

Of course there are many, such as CSDN, Baidu, Ali and so on

If you choose a foreign host, consider the network speed. If you choose a domestic host, consider the stability and security

5.2 Applying for an Account and Setting accounts

Because coding.NET is free, you can create private projects, and the speed is good, here to coding.NET for hosting platform to complete the remote warehouse account application and operation.

5.2.1 Applying for an Account

  1. Open coding.net/ and click the register button in the upper right corner…

  1. Fill in the registration information through the email or mobile phone after the registration is successful, login to the personal home page

If it is QQ mailbox, please pay attention to the activation mail may be in the presence of junk mail, can be found in the dustbin

5.2.2 Creating a Project

After you have logged in, click on the left menu item and click “+” to create a new project. This will create a public project without readme.md, license and Ignore files. The reason is that if you already have a local project and want to submit the new 3 files to the remote repository, you can do so. But beginners to avoid trouble don’t add these three files, enter the relevant information and click create.

5.2.3 Submit source code to a remote repository

There are two ways to create an address:

  • HTTPS type
  • SSH type

HTTPS (recommended for lightweight users)

Use an encrypted web access channel to read and write the repository, and use the user name and password for authentication. Avoid retyping your password. See how to do this without retyping your password for each Push.

Note: Git user name Coding account email or personality suffix, password Coding account password. Note: Hypertext transfer Protocol Secure (HTTPS) push large files may cause errors.

SSH (recommended for experienced users or those who push large files frequently)

Secure Shell (SSH) is a network protocol. As the name implies, it is a very Secure Shell and is mainly used for encrypted transmission between computers. If you use an encrypted channel to read and write from the repository, you need to set SSH Public Key of the account first to complete pairing authentication.

Import repositories can import existing Git projects or SVN projects directly.

Create the project on the command line:

# 1, create directory
$ mkdir project7

# 2, enter the directory
$ cd project7

# 3, initialize the directory as git project
$ git init

# project7(level 1 title)
$ echo "# project7" >> README.md

# 5. Add the description file to the staging area
$ git add README.md

# 6. Commit to the local repository and log
$ git commit -m "first commit"

# 7, add a remote host, the host called origin address to https://git.coding.net/zhangguoGit/project7.git
$ git remote add origin https://git.coding.net/zhangguoGit/project7.git

Git push = 'git push'; -u = 'git push'; -u = 'git push'
$ git push -u origin master
Copy the code

5.2.4 Markdown

Markdown is a lightweight markup language that allows people to write documents in a plain text format that is easy to read and write, and then convert them into valid XHTML (or HTML) documents.

The goal of Markdown grammar is to be a written language for the Web.

1. The title
# Level 1 title
## Secondary title
### Level 3 title
#### Level 4 Title
##### Five-level title
######
Copy the code

List 2.

An ordered list

1. 1
2. 2
3. 3
Copy the code

Unordered list

- 1
- 2
- 3
Copy the code
3. Reference
> This is the quote
Copy the code
4. Images and links

The difference between the two formats is “! “

! [Picture description] (Image links)

[Links to describe] (The link address)
Copy the code
5. Bold and italics
** This is in bold **
* This is italic *
Copy the code
Form 6.
| Tables | Are | Cool |
| ------------ |:------------:| -----:|
| col 3 is | right-aligned| $1600 |
| col 2 is | centered | $12 |
| zebra stripes| are neat | &1 |
Copy the code
7. Code box
with'This wraps the code'
Copy the code
8. The divider

Enter —

Example 9.

Live preview online

5.3 Remote Warehouse Operations

With the Git remote repository account in place and an empty remote repository created, you can now work together with your local repository to simulate multi-player development.

5.3.1 * Common operation commands

Download all changes to the remote repository
$ git fetch [remote]

# Display all remote repositories
$ git remote -v

# Display information about a remote repository
$ git remote show [remote]

# Add a new remote repository and name it
$ git remote add [shortname] [url]

Retrieve the changes from the remote repository and merge with the local branch
$ git pull [remote] [branch]

# Upload local branch to remote repository
$ git push [remote] [branch]

# Push the current branch to the remote repository, even if there is a conflict
$ git push [remote] --force

Push all branches to the remote repository
$ git push [remote] --all

Simple view remote - all repositories$git remoteNew remote warehouse
$ git remote add [branchname]  [url]

# Modify the remote repository
$ git remote rename [oldname] [newname]

# Delete remote repository
$ git remote rm [remote-name]

# Retrieve remote warehouse data$git fetch [remote-name] $git pull [remote-name] $git fetch [remote-name] $git pull [remote-name]$git push origin master
$ git push [remote-name] [branch]
Copy the code

5.3.2 git clone

The git Clone command is used as the first step in a remote operation, usually to clone a repository from a remote host.

$ git clone< Repository address >Copy the code

Example:

$ git clone https://github.com/zhangguo5/AngularJS04_BookStore.git
Copy the code

This command generates a directory on the local host with the same name as the repository on the remote host. If you want to specify a different directory name, you can use the directory name as the second argument to the git Clone command.

$ git clone< Repository address > < Local directory name >Copy the code

In addition to HTTP(s), this command supports SSH, Git, local file protocols, and so on. Here are some examples:

$ git clone http[s]://example.com/path/to/repo.git/
$ git clone ssh://example.com/path/to/repo.git/
$ git clone git://example.com/path/to/repo.git/
$ git clone /opt/git/project.git 
$ git clone file:///opt/git/project.git
$ git clone ftp[s]://example.com/path/to/repo.git/
$ git clone rsync://example.com/path/to/repo.git/
Copy the code

There is another way to write SSH.

$ git clone [user@]example.com:path/to/repo.git/
Copy the code

Git is generally the fastest to download, and SSH is used when user authentication is required.

Refer to the official documentation for a detailed discussion of the pros and cons of the various protocols.

Perform:

Results:

5.3.3 git remote

For administrative purposes, Git requires that each remote host must specify a host name. The git remote command is used to manage host names.

Without an option, the git remote command lists all remote hosts.

$ git remote
Copy the code

Using the -v option, see the web address of the remote host.

$ git remote -v
Copy the code

The above command indicates that there is currently only one remote host, called Origin, and its address.

When you clone a repository, the remote host you use is automatically named Origin by Git.

If you want to use another host name, you need to usegit cloneOf the command-oOption specified.

$ git clone -o WeUI https://github.com/Tencent/weui.git
$ git remote
Copy the code

The preceding command indicates that the remote host is specified as WeUI when cloning.

Git remote show: You can run the git remote show command with the host name to view detailed information about the host.

$git remote show < host name >Copy the code

Git remote add: the git remote add: command is used to add remote hosts.

$git remote add < host name > < url >Copy the code

Git remote rm: command is used to delete a remote host.

$git remote rm < host name >Copy the code

Git remote rename: the git remote rename command is used to rename a remote host.

$git remote rename $git remote rename $git remote renameCopy the code

5.3.4 git fetch

The Git FETCH command is used once the remote host repository has an update/commit (called a COMMIT in Git terms) and those updates need to be retrieved locally.

$git fetch < remote host name >Copy the code

The above command will be a remote host updates, all back to the local.

Git fetch: the git fetch: command is usually used to look at other people’s processes, because the code it fetches has no impact on your local development code.

By default, Git FETCH fetches updates for all branches. You can specify the branch name if you only want to fetch updates for a particular branch.

$git fetch < remote name > < branch name >Copy the code

For example, fetch the master branch of the Origin host.

$ git fetch origin master
Copy the code

Updates retrieved are read as “remote hostname/branch name” on the local host. For example, the master of the Origin host is read by origin/master.

git branch

  • -rOption: Can be used to view remote branches
  • -aOption: View all branches
$ git branch -r
origin/master

$ git branch -a
* master
  remotes/origin/master
Copy the code

The preceding command indicates that the current branch of the local host is master and the remote branch is Origin /master.

After fetching the update from the remote host, you can create a new branch based on it using the git checkout -b command.

Create a new branch based on 'origin/master'
$ git checkout -b newBrach origin/master
Copy the code

You can also merge remote branches on a local branch using the git merge command or git rebase command.

$ git merge origin/master
# or
$ git rebase origin/master
Copy the code

Merge origin/master on the current branch

5.3.5 git pull

Git pull: retrieve updates from a branch on a remote host and merge them with a local branch.

$git pull < git name > < git name >Copy the code

For example, fetch origin’s next branch and merge it with the local master branch:

$ git pull origin next:master
Copy the code

If the remote branch is merged with the current branch, the part after the colon can be omitted.

# next --> Remote branch name
$ git pull origin next
# master --> name of remote branch
$ git pull --rebase origin master
Copy the code

The git pull origin next command fetches the origin/next branch and merges it with the current branch.

* Essentially, this is equivalent to doing git fetch and then Git merge.

$ git fetch origin
$ git merge origin/next
Copy the code

In some cases, Git will automatically establish a tracking relationship between local branches and remote branches. For example, when git clone, all local branches are tracked by default to the remote host branch with the same name. That is, the local master branch automatically “tracks” the Origin /master branch.

Git also allows you to set up tracing relationships manually.

$ git branch --set-upstream-to origin/next master
Copy the code

The above command specifies that the master branch tracks the Origin /next branch.

Why to trace: Git pull can omit the remote branch name if there is a trace relationship between the current branch and the remote branch.

# If the current branch has more than one trace branch, add < remote hostname >
$ git pull origin
Copy the code

This command automatically merges the current local branch with the corresponding origin host, remote-tracking Branch.

If the current branch has only one trace branch, even the remote host name (origin) can be omitted.

$ git pull
Copy the code

The above command indicates that the current branch is automatically merged with the only trace branch.

If the merge requires rebase mode, you can use the –rebase option.

$git pull --rebase < remote host name > < remote branch name >:Copy the code

If a remote host deletes a branch, by default,git pullThe local branch will not be deleted when the remote branch is pulled. This is to prevent the remote host from being operated by someone elsegit pullThe local branch was unknowingly deleted.

However, you can change this behavior by adding the -p parameter to delete remote branches locally after performing git pull.

$ git pull -p
# is equivalent to the following command
$ git fetch --prune origin 
$ git fetch -p
Copy the code

5.3.6 git push

Git push: The git push command is used to push updates from local branches to remote hosts. The format is similar to the git pull command.

$git push < git push >Copy the code

Git pull is < remote branch >:< local branch > and git push is < local branch >:< remote branch >.

If the remote branch name is omitted, the local branch is pushed to the remote branch with which it has a “tracing relationship” (usually both have the same name). If the remote branch does not exist, it will be created.

$ git push origin master
Copy the code

This command pushes the local master branch to the origin master branch. If the latter does not exist, it will be created.

If the local branch name is omitted, the specified remote branch is deleted, as this is equivalent to pushing an empty local branch to the remote branch.

$ git push origin :master
# is equal to
$ git push origin --delete master
Copy the code

The preceding command deletes the master branch of the Origin host.

If there is a tracing relationship between the current branch and the remote branch, both the local and remote branches can be omitted.

$ git push origin
Copy the code

The above command pushes the current branch to the corresponding branch of the Origin host.

Fatal: Fatal: fatal: The current branch dev1 has no upstream branch. To push the current branch and set the remote as upstream, use git push –set-upstream origin dev1.

Enter this command, then enter the user name and password, and push succeeds.

In the future, you just need to type git push Origin!

The default git push behavior is determined by the default git push behavior.
# Before Git 2.0, this property was set to 'matching' by default; after 2.0, it's changed to 'simple'.

You can use git version to determine the current git version (if less than 2.0, update is a better option).
Git config --global push.default 'option' change the default behavior of push.default (or edit the ~/.gitconfig file directly).$git push origin Develop current $git push origin Develop current Push the current branch to the remote branch with the same name. If the remote branch does not exist, the branch will be automatically created. Push the current branch to its upstream branch (this is actually used for situations where you often push/pull from your local branch to the same remote repository. This mode is called Central Workflow) Simple is similar to upstream with one difference: Simple must ensure that the local branch has the same name as its remote upstream branch, otherwise push will be rejected: Push all local and remote branches with the same name. Therefore, if you use a pre-git 2.0 version, pus. default = matching, git push will push the current branch code to the remote branch. Default = simple, if you do not specify an upstream branch for the current branch, you will receive the fatal prompt above.Copy the code

If the current branch has only one trace branch, the host name can be omitted.

$ git push
Copy the code

If the branch is tracked to multiple hosts, you can use the -u option to specify a default host so that git push can be used without any arguments

$ git push -u origin master
Copy the code

Git push = ‘git push’; git push = ‘git push’; git push = ‘git push’;

Git push without any parameters, only the current branch is pushed by default, this is called simple mode. There is also a matching method that pushes all local branches that have corresponding remote branches. Before Git 2.0, matching was the default. Now, simple is the default. To change this setting, use the git config command.

$ git config --global push.default matching
# or
$ git config --global push.default simple
Copy the code

The –all option is used when all local branches are pushed to the remote host, regardless of whether a corresponding remote branch exists.

$ git push --all origin
Copy the code

The above command pushes all local branches to the Origin host.

If the version of the remote host is newer than the local version, Git will report an error when pushing it, requiring you to merge the differences in the local Git pull first, and then push it to the remote host. At this point, if you must push, use the –force option.

$ git push --force origin 
Copy the code

The above command uses the –force option. As a result, the newer version on the remote host is overwritten. Avoid using the –force option unless you are sure to do so.

Finally, Git Push does not push tags unless you use the –tags option.

$ git push origin --tags
Copy the code

These are the common Git operations

๐Ÿ˜† thanks for reading ~ ๐Ÿ’– Special thanks: zhangguo (GitHub: github.com/zhangguo5) ๐Ÿฑ๐Ÿ‘“GitHub Zone