Git Easy Tutorial

Source: Internet
Author: User
Tags version control system

Overview

Before we describe what git is, we need to make a basic overview of versioning (version control), which, in general, is managed and maintained on two dimensions of time and space, and the code itself

And the project files of the organization code (such as makefile or vs project files) are stored on disk space in the form of files and directories, this form of file management is already familiar to everyone, however, how do we manage the various changes we make in different time periods? The version control system, known as VCs, is a system that records the evolution of code changes, and his function is to make it easier for you to retrieve files for a particular period (or version), to see what changes have occurred between versions, to compare changes, or to fix fatal errors.

The version control system has undergone the development of local version control, centralized version control and distributed version control:

    • Local version control system, as the name implies, is a localized version control, without the concept of more advanced versioning such as network collaboration.
    • Centralized versioning (centralized version control System) is a service that runs over there for a version control server that stores and provides all the versions of a project, and in a long period of time dominates, with CVS and SVN as their representative.
    • Distributed versioning (Distributed version control System) overcomes the drawbacks of centralized versioning that may result from a single point of failure, allowing each client to fully mirror items in the entire version control after each checkout operation. In a distributed version control system, any machine can be considered a version control server. Even if one server loses its service capability, other machines and systems can continue to work together to maintain a version control system in operation. Git is a distributed version control system.

The biggest difference between git and other major VCs is that, during a project version update, GIT does not record the change data based on the original file, but rather a series of snapshots (Snapshot, like a small file system) to keep a record of each file. If some files do not change after the version is updated, then in the new version it will be a link to the version of the file that was last updated. In addition, almost all git operations are done locally, so without a "delay", almost all operations are instantaneous. For example, when you want to view the history of a project, you do not have to go to the server to crawl the history and browse directly locally. This means that you can compare the differences between two different versions of the files locally, and you can see in the past which people have made changes and updates to the specified files. Almost completely localized operations have also made it possible for a scenario to occur when someone has to take time to modify and develop their own projects because of a lack of network connectivity, and a version management system is required to document the history of each commit, and Git provides all the conveniences he needs.

Git uses the SHA-1 hash algorithm to encrypt the generated 40-bit string (not the file name) to record everything that represents git. The format is like this:

?? 6bafcdc09f3d6d416f6572f82082987a486d3098

The files in git are mostly in three states, namely:

    • Committed: The file or data is securely stored in the GIT local database
    • Modified: File or data has been modified but not yet commit to the database
    • Staged: file or data has been marked to be placed in the next commit

This mechanism causes the image of git to be made up of three parts (assuming a git directory called Git-repo):

    • Git directory: where all the metadata and objects in your project are stored (git-repo/.git/)
    • Working directory: Here is a separate (by default, the most recent) project version checkout from the GIT Project database to modify and edit files in the specified project version (git-repo/)
    • Staging Area: A simple file stored in Git directory that contains information about the next file to be committed (in git-repo/.git/)
Installation and Configuration

Git can be installed under a variety of operating systems, the following windows, for example, Linux system and Mac OS system users can find Help content on github.com.

It's easy to install git under windows, just by doing the following:

First step: Download Msysgit (http://code.google.com/p/msysgit/), the installation generally only need to keep the default options, just note, do not use putty as a client, GitHub only support OpenSSH. SSH Key needs to be generated after the installation is complete.

The second step: Configure the SSH key, under the user directory (usually C:\Documents and settings\<your_username> under Windows, and the other systems are usually/home/<your_username >) If there is already an SSH configuration, there will be a. SSH directory (the hidden directory), there will be two files (Id_rsa, id_rsa.pub) in the directory, back it up, and then generate a new one, here Cygwin command sequence is as follows

$ ssh-keygen-t rsa-c "<[email protected]>"
Enter file in which to save the key (/C/USERS/<YOUR_USERNAME>/.SSH/ID_RSA):
Enter passphrase (empty for no passphrase):< Here you need to set a password for it >
Enter same passphrase again:< repeat password >
Your identification has been saved In/c/users/<your_username>/.ssh/id_rsa.
Your public key has been saved in/c/users/<your_username>/.ssh/id_rsa.pub.
The key fingerprint is:
???? e8:ae:60:8f:38:c2:98:1d:6d:84:60:8c:9e:dd:47:81 <[email protected]>

Step three: Add public Key to the server you need to submit (here, for example, the other server way to contact the relevant administrator), open your github->ssh public key-> Click "Add another public Key "To copy the contents of your public key (Id_rsa.pub) to GitHub.

Fourth step: Test the configuration is successful, the same, in the Cygwin so input:

$ SSH [email protected]
Error:hi <your_username> You ' ve successfully authenticated, and GitHub does not provide
Shell Access
Connection to github.com closed.

Seeing the above information indicates a successful operation, we can then learn some basic uses.

Local basic operations

First we are going to initialize a repository, if we are completely creating a new project, we can:

mkdir test
CD test
Git init

At this time, the test directory will be more than a directory called. git, the directory will have a config file, his content is as follows:

[Core]
???? repositoryformatversion = 0
???? FileMode = True
???? Bare = False
???? Logallrefupdates = True

We need to add our own user information (note that this information must be consistent with the information you have when configuring SSH):

[User]
???? Name = <your_username>
???? email = <[email protected]>????

Of course, the user information can be configured with the command line, and before the git init command, enter the following command:

git config–global user.name "your_username"
git config–global user.email "[Email protected]"

If the project directory already exists, we can directly:

CD Existing_git_repo
Git init

The next step is some basic operations ...

The first thing to do is git status, which is used to view the status of the current Git image, and we'll use this tool repeatedly in the process of using git:

$ git status
# on Branch Master
#
# Initial Commit
#

Nothing-to-commit (create/copy files and use "Git add" to track)

As you can see, git status gives you quite detailed information, first in the first line is the GIT branch (branch) state information, and then git will tell you that there is no thing to commit to the image, it is recommended to use the command git add to trace the file. So, next we introduce the git add command, assuming that in the working directory using the Python language to write a HelloWorld applet, after the code is saved, we get a hello.py file, and then we want to have this file is GIT image tracking (track) to , then you only need to:

$ git Add hello.py

In this way, we will add hello.py to the GIT image for versioning and use Git status again to view the current mirroring status:

$ git status
# on Branch Master
#
# Initial Commit
#
# Changes to be committed:
# (use "Git rm–cached ..." to Unstage)
#
# New file:hello.py
#

Note that here it mentions changes to being committed, meaning that the file is already in staged state, then you can commit it according to your own needs, or if you think this is a misoperation, the file should not be submitted, you can go through git rm –cached command to cancel its staged status (you will find the exact hint in the status information).

Now, we commit the hello.py by ordering git commit:

$ git commit

At this point, there will be a text with status information for you to edit (using what the editor depends on your configuration of Git), the "#" at the beginning of the comment line to enter some text, to comment on this submission, to facilitate the maintenance and understanding of other code collaborators!

You can also use the command parameter-m to directly enter the comment content, speeding up the submission speed:

$ git commit-m "comment here"

At this point, your file hello.py is already in the tracked state!.

Now, we have a hello.py in the mirror, and then, assuming that a small error is found, such as a cyclic condition is wrong, then we need to complete the modification for the file, then, when we again git status:

# on Branch Master
# Changed but not updated:
# (use "git add ..." To update what'll be committed) # (use git che
# ckout-... "To discard changes in working directory)
#
# modified:hello.py
# no changes added to commit (use "git add" and/or "Git Commit-a")

Git status shows that hello.py has been modified, if you want to commit, you need to git add the file again, or you can directly use Git commit-a skip the Add step, directly submit (not yet track the file must first git add to commit).

In the tip, there are also mentions that if you want to undo the changes to the hello.py, you can use the git checkout command to implement, here is the case:

$ git checkout–hello.py

If you do this, you will find that your hello.py is back to the state that was not modified before. In the Unix/unix-like system, there will almost be a small contrast file with different tools called diff, in Git also has a tool to compare the file you are prepared to commit to the changes in the state before the difference between, well, perhaps you guessed that this command is Git diff.

Now we're trying to change the hello.py again and run git diff:

$ git diff
Diff–git a/hello.py b/hello.py
Index befc634: a86316b 100644
-a/hello.py
+ + b/hello.py
@@ -1,3 +1,4 @@
+/* New Comment Line * *
if __name__ = = "__main__":
Print "Hello, world!"

With Git's diff tool, it's easy to see where we've changed. At this point, if we want to undo the previous changes, we can use the git reset command:

$ git reset HEAD hello.py
$ git status
# on Branch Master
# untracked Files:
# (use "git add ..." to include in what'll be committed)
#
# hello.py

Nothing added to commits but untracked files present (use "Git add" to track)

Again git status,hello.py back to the untracked state!

Next If you need to modify the file name of the README.txt (usually the Readme file for the project) (remember that our files are versioned in Git's image, do not use the UNIX command MV or RM directly to perform normal file operations on files in a git image), we should use Git MV Command:

$ git mv README.txt tutorial.txt
$ git status
# on Branch Master
# Changes to be committed:
# (use "Git reset HEAD ..." to Unstage)
#
# Renamed:README.txt-Tutorial.txt
#
$ git commit-a-M "renamed a File"
[Master 55ce30d] renamed a file
1 files changed, 0 insertions (+), 0 deletions (-)
Rename README.txt = Tutorial.txt (100%)

As you can see, after committing the change, README.txt is successfully renamed in the file system and in the GIT image in order to tutorial.txt. Similarly, you can unstage to undo the renaming of the file, the choice is yours!

If we no longer need to tutorial.txt this file, we can remove it from the git image, and git rm is the command to delete the file:

$ git rm tutorial.txt
RM ' Tutorial.txt '
$ git status
# on Branch Master
# Changes to be committed:
# (use "Git reset HEAD ..." to Unstage)
#
# Deleted:tutorial.txt
#
$ git commit-a-M "deleted a file"
[Master 7d81981] deleted a file
1 files changed, 0 insertions (+), 1 deletions (-)
Delete mode 100644 tutorial.txt????

As mentioned earlier, these operations can be restored because Git is a version control system, so there is a natural version history management mechanism.

We can use the tool git log to provide a commit history to view the Git image:

$ git log
Commit 7d819818530ce89322019ba5000723c973eb0420
Author:ghostm55
Date:sun Mar 14 15:26:22 2010 +0800

deleted a file

Commit 55ce30d88fb5c81d20bdf86e2034053613fed632
Author:ghostm55
Date:sun Mar 14 15:11:39 2010 +0800
Renamed a file
Commit 2ED9F1F9BD1A7561CD7E57DCDBD7F2CDA54668FB
Author:ghostm55
Date:sun Mar 14 14:58:11 2010 +0800
A little change

It's basically clear that Git has a detailed record of each commit's information (checksum value, submitter information, commit time).

The following is a simple branch management operation, GIT branch management is the exception of the simple and convenient, you can use the Git Branch command for very intuitive operation:

You can see how many branches of the current project exist in the working directory first:

$ git Branch
* Master
Test

It can be clearly seen that there are currently two branch master and test in the project, with * is the current branch (we can use the command git checkout test to switch to test instead). Next we add a branch to the project:

$ git Branch New
$ git Branch
* Master
New
Test

We see that the new branch has been added to the GIT image, and if we want to delete the branch, we can:

$ git branch-d New
Deleted Branch New (was 63c0da1).
$ git Branch
* Master
Test

At this point we see that new is not in the mirror, and when we need to merge the code from the specified branch into the default branch, you can use the command:

Remote Basic operation

(This section refers to a network blog:http://archive.cnblogs.com/a/2050324/)

To participate in the collaboration of any Git project, you must know how to manage the remote repository. A remote repository is a project repository that is hosted on a network, and there may be several, some of which you can only read, and others that you write. When you collaborate with others to develop a project, you need to manage these remote warehouses to push or pull data and share the progress of your work. Manage remote repositories, including adding remote libraries, removing obsolete remote libraries, managing various remote library branches, defining whether to track these branches, and so on. In this section we will discuss the management and use of remote libraries in detail.

View the current remote library

To see which remote repositories are currently configured, you can use the GIT remote command, which lists a short name for each remote library. After you have cloned a project, you can see at least one remote library named origin, and Git uses that name to identify the original repository you cloned by default:

$ git clone git://github.com/schacon/ticgit.git
Initialized Empty Git repository in/private/tmp/ticgit/.git/
Remote:counting objects:595, done.
Remote:compressing objects:100% (269/269), done.
Remote:total 595 (Delta 255), reused 589 (Delta 253)
Receiving objects:100% (595/595), 73.31 KiB | 1 kib/s, done.
Resolving deltas:100% (255/255), done.
$ CD Ticgit
$ git remote
Origin

You can also add the-V option (this is shorthand for –verbose, take the initials) and display the corresponding clone address:

$ git remote–v
Origin Git://github.com/schacon/ticgit.git

If there are multiple remote warehouses, this command is all listed. For example, in my Grit project, you can see:

$ CD Grit
$ git remote–v
Bakkdoor Git://github.com/bakkdoor/grit.git
Cho45 Git://github.com/cho45/grit.git
Defunkt Git://github.com/defunkt/grit.git
Koke Git://github.com/koke/grit.git
Origin [Email protected]:mojombo/grit.git

In this way, I can easily pull their commits from these users ' warehouses locally. Please note that the address listed above only has an SSH URL link for Origin, so there is only this repository I can push

Data up (we'll explain why in the fourth chapter).

Add a remote repository

To add a new remote repository, you can specify a simple name for future reference, run git remote add [shortname] [url]:

$ git remote
Origin
$ git remote add PB git://github.com/paulboone/ticgit.git
$ git remote–v
Origin Git://github.com/schacon/ticgit.git
PB Git://github.com/paulboone/ticgit.git

It is now possible to use the string PB to refer to the corresponding warehouse address. For example, to crawl all the information that Paul has but the local repository does not have, you can run git fetch PB:

$ git fetch PB
Remote:counting objects:58, done.
Remote:compressing objects:100% (41/41), done.
Remote:total (Delta), reused 1 (Delta 0)
Unpacking objects:100% (44/44), done.
From Git://github.com/paulboone/ticgit
* [New branch] master, Pb/master
* [New branch] Ticgit-Pb/ticgit

Now, Paul's Trunk branch (master) is fully accessible locally, with the name Pb/master, you can merge it into one of your branches, or switch to this branch to see what interesting updates are.

Fetching data from a remote repository

As you've seen before, you can fetch data from the remote repository locally using the following command:

$ git fetch [remote-name]

This command pulls all data that is not in your local repository to the remote repository. Once the operation is complete, you can access all the branches in the remote repository locally, merge one of the branches locally, or simply take out a branch to explore. (We'll discuss the concepts and operations of branching in detail in Chapter three.) )

If a repository is cloned, this command automatically attributes the remote repository to Origin. So, GIT fetch origin crawls all the updates that someone else uploaded to the remote repository since you last cloned (or someone else has submitted an update since the last fetch). It is important to remember that the fetch command simply pulls the remote data to the local repository and does not automatically merge into the current branch of work, but only when you are ready to do so manually. (Note: You need to create a remote repository beforehand, then execute: Git remote add [warehouse name] [Warehouse url],git fetch [remote warehouse name] to crawl the remote warehouse data to local, and then git merge remotes/[warehouse name]/ Master can merge the remote repository to the local current branch. This branching approach is more appropriate for independent-integrated development, i.e., after each development test is well integrated. For example, Android's framework and AP development.

You can use the –bare option to run git init to set up an empty repository, which initializes a warehouse that does not contain a working directory.

$ cd/opt/git
$ mkdir Project.git
$ CD Project.git
$ git–bare Init

At this point, Join,josie or Jessica can add it as a remote repository, push a branch, and then upload the first version of the project to the warehouse. )

If a branch is set up to track a branch of a remote repository (see the next and third chapters), you can use the git pull command to automatically crawl the data down and then automatically merge the remote branch into the current branch in the local repository. We often use this in our daily work, both fast and well. In fact, by default, the git clone command essentially automatically creates a local master branch to track the master branch in the remote repository (assuming the remote repository does have a master branch). So we typically run git pull to merge the data from the remote repository of the original clone into the current branch in the working directory.

Push data to a remote repository

Project to a stage, to share with others the current results, you can push data from the local warehouse to the remote repository. The command to implement this task is simple: git push [remote-name] [branch-name]. If you want to push the local master branch to the origin server (again, the clone operation will automatically use the default Master and Origin names), you can run the following command:

$ GIT push origin master

This command completes the task as expected only if there are write permissions on the cloned server, or if no one else is pushing the data at the same time. If someone else has pushed a few updates before you push the data, your push will be dismissed. You have to crawl their updates locally and into your project before you can push them again. For more information about pushing data to a remote repository, see Chapter Iii.

View Remote Warehouse Information

We can view the details of a remote repository by ordering git remote show [remote-name], for example, to see the cloned Origin repository, which can be run:

$ git Remote show origin
* Remote origin
Url:git://github.com/schacon/ticgit.git
Remote Branch merged with "Git Pull" while on branch master
Master
Tracked remote Branches
Master
Ticgit

In addition to the corresponding clone address, it also gives a lot of additional information. It's a friendly way to tell you that if you're in the Master branch, you can use git pull commands to merge the data locally. It also lists all the remote branches that are in the tracking state.

During the actual use, the information given by Git remote show might look like this:

$ git Remote show origin
* Remote origin
URL: [email protected]:d Efunkt/github.git
Remote Branch merged with "Git Pull" while on branch issues
Issues
Remote Branch merged with "Git Pull" while on branch master
Master
New Remote branches (next fetch would store in Remotes/origin)
Caching
Stale Tracking branches (use ' git Remote prune ')
Libwalker
Walker2
Tracked remote Branches
Cc.
Apiv2
Dashboard2
Issues
Master
Postgres
Local branch pushed with ' git push '
Master:master

It tells us what branch is the default push when running Git push (the last two lines). It also shows which remote branches are not synchronized to the local (caching branch on line sixth), which have been synchronized to the local remote branch has been deleted on the remote server (Stale tracking branches the two branches below), and running Git pull will automatically merge which branches (the issues and master branches listed in the first four rows). (This command can also view the correspondence between the local branch and the remote Warehouse branch.) )

Deletion and renaming of remote warehouses

In the new version of Git, you can use the GIT remote rename command to modify a remote repository's short name, such as to change the PB to Paul, so you can run:

$ git remote rename PB paul
$ git remote
Origin
Paul

Note that renaming a remote repository also causes the corresponding branch name to change, and the original Pb/master branch is now Paul/master.

If you encounter a remote repository server migration, or if the original clone image is no longer in use, or if a participant no longer contributes code, you need to remove the remote repository and run the GIT remote RM command:

$ git remote RM Paul
$ git remote
Origin

Recommended Books

Version control-Using Git

Subtitle:-Using Git

Author: Travis Swicegood

Translator: Dong Yue/Shao Zhaowei/Translation

Publishing house: Electronic Industry publishing house

Publication year: May 2010

?

The Git authoritative guide

Author: Shing

Publishing House: Machinery Industry Press Company

Publication year: June 2011

?

?

Git Easy Tutorial

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.