Git Tutorials (notes)

Source: Internet
Author: User
Tags tagname using git version control system

Read the Liaoche to write tutorials, down to the end, took three days to learn, do a study note it

About Git

Linus created Linux to facilitate the management of Linux code, the use of C wrote this distributed version control system. The GitHub site was launched in 2008, providing free git storage for open source projects.

Centralized vs Distributed:
Centralized version control system, version inventory on the central server, everyone with their own computer, use the time to obtain a new version from the server, work is finished and then pushed to the central server. The disadvantage is that it must be networked and inefficient.
Distributed version control system, no central server, everyone's computer is a full version of the library, work without the need for networking, to achieve collaboration, everyone only need to change their own parts to the other side. There is usually a computer to serve as a central server, just to facilitate the exchange of changes. Distributed security is even higher.

Install Git

Linux, Unix, Mac, and Windows can run git on several platforms, and the most common Linux only records the installation on Linux.
First, try typing git into the shell to see if there is a setup:

Installation in Ubuntu is simple, a command sudo apt-get install git
If in other Linux version can go to git official website download source code, unzip after input:./config, make, sudo makes install
After installation, set up for the local git library:
$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"

To create a version library

1. Create a git library
The right place to create an empty directory, enter the directory after the git init command to make this directory can be managed warehouse;
$ mkdir git
$ cd git
$ git init

Note that a hidden folder is generated when the warehouse is created. Git, which is used to track administrative versions and cannot be modified at will

2. Add files to the GIT library
Note that the version control system can only track changes to text files, and cannot track changes in binary files.
Add a file in two steps:
The first step is to add files to the repository using the command git add
Second, use the command git commit–m "XXX" to submit changes, quotes for instructions, general input change record

View library status, modify files

If you modify a file, you can run the git status command to view the status

The above shows that the file has been modified but not ready for submission.
Although Git tells us that the Test.txt file has been modified, but does not show exactly what was changed, this time the git diff command is needed to see

The result shows a sentence added to the second line.
Once you have a clear idea of what changes you can submit to your warehouse, committing the changes is the same as submitting a new file:
git add test.txt
Before performing the second part, run GIT status again to see the status of the current warehouse:

Found changes ready to submit, the next step can be assured that the submission:
Git commit–m "Add one line"
Once submitted, you can view the status again:

Summarize:
? git status to see the status of your current workspace
? If Git status tells you that a file has been modified, use Git diff to see what's changed to decide whether to commit the change

Version return

After constantly making changes to the file and then committing the changes to the repository every time, committing to git is like saving a "snapshot", which in git is called a commit and can be restored to the latest version at any time.
First, use the git log command to view the history:

You can see the commit log from the most recent to the farthest, and if it shows too much confusion, add the –pretty=oneline parameter:

Each change shows the commit ID (version number) and the change in only one line.
Okay, now you're ready to fallback the Test.txt file to the previous version:
In Git, head represents the current version, the previous version is head^, and the last version is head^^, which is written as a head~100 in the current 100 versions.
Use the git reset–hard head^ command to fall back to the previous version:

You can see back to the first version, and then use git log to view the version history:

Found before the version is missing, like you from 21st century to sit the time shuttle machine came to 19th century, want to go back to 21st century has not gone back, swollen?
There is still some way, as long as you can find the previous version of the commit ID (version number) can be, using Git reflog to view each command:

If the previous version number is afa4020, then you can revert to which version:

Note: The version number is just the first few, not the whole (all too long 0-0), Git will be based on the first few automatically to find
Summarize:
? The HEAD points to the current version number, and Git allows the shuttle between different versions, Git Reset–hard commit_id
Before the shuttle, use git log to view the history to determine which version to return to
To return to the future, use Git reflog to view the history command to determine the future version number

Workspaces and Staging Area

A workspace is a directory that can be seen on a computer, such as a previously created directory git is a workspace;
Repository, there is a hidden directory in the workspace. Git, this is the repository.

The most important part of the repository is the staging area called stage, the first branch master that was created automatically, and the pointer to Mater head.
The previous sections mentioned adding files to the repository in two-step execution:
The first step git add is actually adding files to the staging area;
The second git commit commit modification is to commit the contents of the staging area to the current branch, and the staging area will be emptied.

Manage changes

This section is also to learn more about Git's working mechanism.
For example, we make a modification to a file and then add: git add filename
The file is then modified for the second time without executing the add command and then executing git commit-m "..."
We will find that only the first modification was submitted and the second modification was not submitted. This means that git manages the changes and does not modify the workspace files.

Undo Changes

Situation One: modified file, but no add to staging area, need to undo the file modification: git checkout–test.txt or manually restore the changes
Situation two: After modifying the file add to the staging area, and again modify the file, you need to undo the second modification: git checkout–test.txt equivalent to restore staging area to the workspace, when staging area has the first change to commit to the branch.
Situation three: After modifying the file add to the staging area, need to undo the changes: git reset HEAD test.txt Delete the staging area, the workspace is still modified not undone, and then git checkout–test.txt undo the changes in the workspace
Situation four: Modified add and commit, need to undo the changes: Git Reset–hard head^ is the version return

Summary: One sentence summary is git checkout– will make the file back to the last git commit or git add before the state of the file, this place a bit around, it must take time to figure out ....

deleting files

Delete a file in the workspace rm Test.txt, this time the workspace and the repository is inconsistent, git status will tell you that the files are deleted, there are now two options:
I do want to remove it from the repository
git rm test.txt
git commit –m “remove test.txt”

Second, recover deleted files:
git checkout – test.txt

Remote Warehouse

We can build our own git server on our own, and at this stage there is a magical Web site GitHub that offers git repository hosting services, so just sign up for a GitHub account for free: Open https://github.com/pricing for registration.
The transfer between the local git library and the remote GitHub repository is encrypted via SSH, so a bit of setup is required:
The first step is to create an SSH Key. In the user home directory, see if there is no. ssh directory, if you have to look at the directory there are no Id_rsa and id_rsa.pub two files, if any, can be directly next; if not, open the shell to create
$ ssh-keygen –t rsa –C “your email [email protected]***.com”
At this point in the home directory under the. SSH directory there are id_rsa and id_rsa.pub two files, Id_rsa is the private key, Id_rsa.pub is the public key
Second step, login to GitHub, open the settings, in the left SSH keys to add, click "New ssh Key", the title any fill, in the Key text box paste Id_rsa.pub file content.
GitHub can then recognize your computer and allow you to push changes. Multiple computers can add multiple public keys.
After logging in to GitHub, add the new Respository button in the upper right corner to create a fresh warehouse. Fill out git in the respository name, and the other remains the default, creating a new Git repository successfully. Currently, this warehouse is still empty, first we associate the local git repository with our remote repository:
$ git remote add origin https://github.com/JasonLiu1991/git.git
Be careful to replace JasonLiu1991 with your GitHub account name.
Once added, the remote library's name is origin, which is the default term for git, or it can be changed to another
Commands commonly used in this place:
When git remote does not have an option, it is listing all remote hosts:

The Git remote-v-v option is to view the URL of the remote host:

git remote Show < hostname > View details about this host
Git remote Add < host name > < URL > Add host
GIT remote RM < host name > delete a host
Git remote Rename < host name > < new hostname > Rename

The next step is to push the contents of the local library to the remote library:
$ git push –u origin master
The command means that the local master branch is pushed to the remote Origin host.
Because the remote library is empty, the first time you push the master branch with the-u parameter, git will not only push the master branch to the remote Master branch, but will also associate the local master branch with the remote Master Branch for later convenience.
At this point, on the GitHub page, you will see the synchronization of the content, and later local changes submitted by the command:
$ git push origin master
At this point, we have a complete distributed repository.

The git Push command is detailed:
$ git push <远程主机名> <本地分支名>:<远程分支名>
If the remote branch name is omitted, the local branch is pushed to the remote branch with which the trace relationship exists and is created automatically if the remote branch does not exist. Git push origin master pushes the local master branch to the master branch of the Origin host. If the latter does not exist, it will be created.
If the local branch name is omitted, the specified remote branch is deleted because it is equivalent to pushing an empty local branch to the remote branch
$ git push origin :master
Equivalent to
$ git push origin --delete master

Note:
There is also a problem is that every time you push the need to enter the account name password, a bit of trouble, the solution:
There is a. git directory under the directory of the local Git repository, and. Git has a config file,
The URL = https://github.com/jasonliu1991/git. Git replaces:
url = Https://[username]:[password] @github. Com/jasonliu1991/git. Git can

Cloning from a remote library

$ git clone <版本库的网址>The command will generate a local directory with the same name as the remote repository.

Branch Management

In the version return section, each time you commit git, they are strung into a timeline, which is a branch of the line. There is currently only one time line, called Master Branch Master. Master points to the commit, and head points to the current branch:

Each commit, Master moves forward one step.
When we create a branch, for example, Dev,git creates a new pointer called Dev, which points to the same commit as master when it is created, and head to Dev, which indicates that the current branch is on Dev:

As you can see, Git creates a branch that adds a pointer, moves the head, and the file doesn't change.
From now on, the workspace has been modified for the Dev branch, such as commit changes, which is the dev move one step forward:

If the work on Dev is done, you can merge dev into master by pointing the master pointer directly to the current commit of Dev:

You can even delete the dev branch after the merge is complete.
When the principle is clear, start the operation.
First, set up branch Dev, and switch to branch Dev
$ git checkout -b dev
The parameter-B means create and switch, equivalent to the following two commands:
$git branch dev 创建分支
$git checkout dev 切换到分支
$ git branch 查看当前分支,前面带*号表示当前分支:


Now we're going to commit the changes that happen on the Dev branch, and of course you can switch at any time: Git branch Master
After switching back to the master branch, we want to merge the work of Dev into master:
$ git Merge dev
The git merge command is used to merge the specified branch to the current branch:

You can see that it is fast-forward, which is fast merging.
After the merge is complete, you can delete the dev branch:
$ git branch –d dev
Summary:
GIT encourages the use of branching:
View branches: Git branch
Create a branch: Git branch
Switch branches: git checkout
Create + Switch branch: Git checkout-b
Merge a branch to the current branch: git merge
Delete branch: Git branch-d

Resolve Conflicts

Conflicts are encountered when merging, for example:
Create a new branch Feature1
$ git checkout –b feature1
Modify the last line of the file, add the ttttttt character, and commit the modification
Switch back to the main branch, modify the file again, add the PPPPPPPP character to the last line, commit the changes
Now the two branches each have different commits:

Now merge, there will be conflicts:

Prompt for conflicts, must be resolved before committing changes
Git uses <<<<<<<,=======,>>>>>>> to mark different branches of content, and we manually modify it to commit

We git log --graph --pretty=oneline can see the merging of the branches in the following cases:

Branch management policies

In the fast forward mode described earlier, branch information is lost after the branch is deleted.
If you want to forcibly disable Fast forward mode, GIT will generate a new commit at merge, so you can see the branching information from the branch history.
Command: git merge --no-ff –m “******” dev
Because this merging is to create a new commit, add the-m parameter. This will enable you to view the branch history with log: git log --graph --pretty=oneline
Without using fast forward mode, the principle

Branching policy:
In the actual development, we should follow several basic principles of branch Management:
First of all, the master branch should be very stable, that is, only to release the new version, usually do not work on it;

So where do you work? Work on the Dev branch, that is, the dev branch is unstable, at some point, such as the 1.0 release, then merge the Dev branch to master and release the 1.0 version in the Master branch;

You and your little friends each work on the Dev branch, and everyone has their own branch, and it's time to merge on the Dev branch.
So, the branch of teamwork looks like this:

Bug Branch

Software development often needs to fix bugs, in git, each bug can be repaired by a new temporary branch, repaired, merged, and then deleted.
Well, when it comes to the task of repairing a bug with a code name of 101, it is natural to create a branch issue-101 to fix it, but, and so on, the current work on Dev has not been completed do not want to submit, how to do?
Fortunately, Git provides a stash feature that temporarily stores the work site and restores it back to work when needed:

You can now safely fix the bug, if you need to fix the bug on the master branch, create a branch from master:

After the repair, switch to the master branch, complete the merge, and finally delete the ISSUE-101 branch is complete.
When the bug is fixed, it's time to go back to the dev branch and work, and now you need to restore the previously stored workspace:
Two methods:
First git stash the list command to see:

Method one, Git stash apply recovery, but after recovery stash content does not delete, need to use git stash drop to delete
Method Two, Git stash pop, restore while deleting
Of course, you can stash multiple times, restore it with git stash list, and then restore the specified stash:
$ git stash apply [email protected]{0}

Summary:
When fixing a bug, we will fix it by creating a new bug branch, then merging and finally deleting;
When the work is not finished, first put the work site Git stash, and then to fix the bug, repair, then git stash pop, back to the job site.

Feature Branch

To develop a new feature, it is better to create a new branch;

If you want to discard a branch that has not been merged, you can forcibly delete it via Git branch-d.
git branch–d Deleting a branch that has not been merged will prompt you to fail.

Multi-person collaboration

The working mode of multi-person collaboration is usually this:
First, you can try to git push origin branch_name push your own changes;
If the push fails, because the remote branch is more than your local update (other small partners are also committed), you need to first try to merge with Git pull;
If there is a conflict in the merge, resolve the conflict and submit it locally;
No conflict or conflict resolution, and then git push origin branch_name push to Succeed!
Note: If git pull prompts "No tracking information", then the link relationship between the local branch and the remote branch is not created, using the command git branch --set-upstream branch_name origin/branch_name .

Summary:
Push the branch from the local, use git push origin branch-name , if push fails, first crawl the remote new commit with git pull;
Local and remote branches corresponding to the branch, use git checkout -b branch-name origin/branch-name , local and remote branch names are best consistent;
Establishing the Association of local and remote branches, using git branch --set-upstream branch-name origin/branch-name ;
From a remote crawl branch, use git pull, and if there is a conflict, deal with the conflict first.

Label Management

When we publish a version, we usually start with a tag (tag) in the repository, so that it is the only version that determines the time of the tag.
To create a label:
Switch to the branch that needs to be labeled, then git tag v1.0 can hit a new tag, git tag to see the existing tag:

To tag a version of history, you only need git log to view the ID of the historical commit:

git show <tagname>Git show can see the details of the tag
You can also create labels with descriptions,-A to specify label names,-M to specify descriptive text
$ git tag –a v0.1 –m “version 0.1 released” 9e93424

Action Label:
If the label is wrong, you can delete it:
$ git tag –d v1.0
Because the created label is stored locally, it has not been pushed to the remote
To push a tag: $ git push origin <tagname>
To push all the labels that have not been pushed: $ git push origin –tags
If the label has been pushed to the remote, to remove the remote label on the point of trouble, click to start the local delete:
$ git tag –d v0.9
Then remotely delete:
$ git push origin :refs/tags/v0.9

customizing git

For example, let git display colors:
$ git config --global color.ui true
Ignore special files:
Some files in the workspace do not want to be submitted to the remote, but each git status will show untracked files ...
To make git ignore certain files, you need to create a special. gitignore file in the workspace, and then fill in the ignored file name, noting that the. gitignore file itself needs to be placed in the repository.

Setting aliases

For example, git status is not good to knock, can be set to git St, specific commands:
$ git config --gobal alias.st status
Now knocking git st effect equals git status
Commonly used for:
$ git config --global alias.co checkout
$ git config --global alias.ci commit
$ git config --global alias.br branch

The git reset HEAD file command is to undo the changes in the staging area (Unstage) and back into the workspace to set aliases:
$ git config --global alias.unstage ‘reset HEAD‘
There are even people who have been desperate to configure LG as:
git config --global alias.lg "log --color --graph --pretty=format:‘%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset‘ --abbrev-commit"
The effect is cool:

Note: When you configure Git, the –global parameter means it works for the current user, if not, only for the current warehouse

Configuration file:
Each warehouse has a configuration file,. git/config
Each user also has a profile in the user's home directory. Gitconfig

Finally attach the original address of the reference two great gods:
Liu Xuefeng
http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000
Nanyi
Http://www.ruanyifeng.com/blog/2014/06/git_remote.html

Git Tutorials (notes)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.