Git 分布式版本控制系统

Git 作为较新的版本控制系统,相对于 SVN 的最大特点就是它是分布式的。因此它的工作流程和 SVN 相比就有所不同了。首先需要将远程的 Git 版本库克隆(clone)下来,然后在本地修改后先提交(commit)到本地版本库,最后再推送(push)本地的所有修改到远程的版本库中去。

一、基本用法

最常见的使用方式就是类似这样的:

克隆代码: git clone https://github.com/user/project.git
添加修改: git add *
提交修改: git commit -m "some log message"
推送修改: git push origin master

由于整个版本库都克隆下来了,我们可以在本地作任意多次的提交,以后再推送所有的修改。这样在离开网络时也能继续工作,连接网络后马上就能同步到最新的代码状态了(使用 git pull 命令)。

二、分支管理

Git 中也可以使用多个分支,基本的方法如下面的例子:

创建分支:git checkout -b newbranch
推送分支:git push origin newbranch
切换分支:git checkout master
合并分支:git merge newbrahch
删除分支:git branch -d newbranch

在上面的例子中,master 是默认的主分支,而 newbranch 是新创建的分支,再分支中修改测试完毕后,我们用 git merge 命令将 newbranch 分支上的修改合并到 master 主分支中来,然后删除 newbranch 分支。

分支合并后得到的是一个有分叉的提交历史。如果要得到线性的提交历史,可以用 rebase 命令。例如:

切换分支:git checkout newbranch
衍合分支:git rebase master

三、仓库管理

在 Git 中还可以将版本库推送到多个远程服务器上。例如:

添加新的远程服务器:git remote add another http://example.com/repository
推送到原始的服务器:git push origin master
推送到另外的服务器:git push another master

其中,origin 是我们刚开始时用 git clone 命令时添加的默认远程服务器名称,another 是另外的远程服务器的名称。

四、特殊用法

修改远程仓库的 URL 地址:

git remote set-url origin git://new.example.com/newrepo.git

创建孤立分支:

git checkout --orphan newbranch

克隆单一分支:

git clone -b somebranch --single-branch git://some.example.com/reponame.git

参考资料:

[1] git - the simple guide
[2] Git for Windows - msysgit
[3] 
tortoisegit - Porting TortoiseSVN to TortoiseGit
[4] A successful Git branching model
[5] 懒惰的程序员 : git merge --squash 介绍
[6] Git Book 中文版 - rebase
[7] 高飞鸟 Highbird  - Git rebase 的应用
[9] Git Book 中文版 - 储藏
[9] GitHub tip: easily sync your master to GitHub Pages
[A] Setup "gh-pages" branch and "master" branch as subfolders
[B] Git - How do you clear the staging area?

注记:2013 年 6 月 2 日更新。

原文地址:https://www.cnblogs.com/zoho/p/2542141.html