Git
Git简介
**Git**是由Linus Torvalds创造,Linus开发了Linux操作系统并将其开源,初代是由BitKeeper管理和维护Linux的开源代码。至2005年,BitKeeper的商业公司终止了和Linux内核开源社区的合作。于是,Linus创造了Git用以管理维护代码。
Git 与Svn对比
Svn
**Svn**是集中式版本管理工具,,通过采用分支管理系统的高效管理,简而言之就是用于多个人共同开发同一个项目,实现共享资源,实现最终集中式的管理。
 集中管理方式在一定程度上可以看到开发人员在干什么,而管理员页可以轻松掌握每个人的开发权限。 但是同时其缺点也是十分明显:
- 服务器单点故障
- 容错性差
Git
Git是分布式的版本控制系统,没有中央服务器,每个人的电脑上都有一个完整的版本库(本地仓库),这样工作的时候就不需要联。而在多人协作方面,每个人只需将各自的修改传递传送给对方,就可以看到对方的修改了。 
Git的工作流程
一般工作流程如下:
- 从远程仓库中克隆Git资源作为本地仓库
- 从本地仓库中checkout代码然后又进行代码修改
- 在提交前先将代码提交到暂存区
- 提交修改。提交到本地仓库。本地苍库中保存修改的各个历史版本
- 在修改完成后,需要和团队成员共享代码时,可以将代码push到远程仓库。

Git的安装
Git安装地址
Git的使用方法
创建本地仓库
在安装好Git后,我们需要先创建本地仓库(repository),将来我们要把所有的文件放置到我们新建的这个版本库里面,便于Git管理。
创建本地仓库:mkdir 仓库名称
例如在C盘中创建一个名为:firstProject的仓库
 然后我们就可以在C盘中看到这样一个空的文件夹 
然后我们就要把这个文件夹,设置成Git可以管理的仓库。 首先需要显示当前目录
显示当前目录命令:pwd
 然后,将该目录设置为Git可管理仓库
将当前目录设置为Git可管理仓库:git init
 这样就设置成功了,如上图,当我们使用git init 命令后,在当前目录下得到了一个初始化后的一个后缀为“.git”的仓库。
添加文件进Git仓库
要添加文件进入Git仓库
1. 在仓库目录下新建待加入文件
找到本地仓库,在里面添加待加入的文件 
2. 将文件添加入暂存区
将文件加入暂存区命令 git add 文件 
3. 将文件提交至仓库
提交命令:git commit git commit -m “XXX” 其中“XXX”部分是对本次提交的说明,便于日后检索以及其他人阅读使用
 发现我们在递交文件前还需要进行配置作者身份
身份配置 git config --global user.email “XXX” git config --global user.name"XXX"
配置完成后再递交文件  递交成功后,我们可以通过查看文件的提交状况,来检查是否还有文件没有提交
查看文件提交状况: git status
 说明没有文件需要提交了。 在我们修改过已经上传文件后,在查看Git提交文件的状态   这里表明文件被修改,但修改部分还在暂存区未被提交。
查看文件区别(文件的修改部分): git diff 文件
 这里就可以呈现出来被修改的部分,然后知道修改部分后,就可以将其再次提交仓库了。 
版本回退
预先对test.txt文件进行几次修改,偶尔会出先如下图的报错: 
这个index.lock文件,是在进行某些比较费时的git操作时自动生成,操作结束后自动删除,相当于一个锁定文件,目的在于防止对一个目录同时进行多个操作。有时在强制关闭进行中的git操作后,这个文件没有被自动删除,之后就无法进行其他git操作,必须手动删除。
手动删除index.lock文件:git clean -f .git/index.lock
我们先对该版本进行几代修改  在一次工程当中我们往往要多次的反复修改一个文件,所以可以对版本库进行回退是十分重要的操作
将版本回退到上一个版本: git reset --hard HEAD^ 将版本回退到上上一个版本: git reset --hard HEAD^^ 其余一次类推

查看版本的历史记录信息: git log 
上图中,进行回退操作完了以后,HEAD is now at cf59207 1st,这个cf5927就是版本号
查看版本号:git reflog
 根据版本号,我们可以自由切换版本
切换到对应版本号版本:git reset --hard 版本号

Git改撤删文件操作
如果当我们需要对版本文件的修改时,我们可以采取三种方案:
- 直接更改文件再提交
- 版本回退
- 使用Git命令对文件进行修改
撤销工作区文件
我们对文件进行一些修改  红体字说明,文件已被修改当时还未被提交到暂存区,我们可以对其进行撤销操作。
撤销工作区中的文件修改:git checkout – 文件
 这样就清除成功了。
文件删除
现在仓库里新建一个新的文件  然后上传并关联 
移除版本库下文件:git rm 文件 若要彻底删除,需要移除后需要再次commit变化
rm移除与git rm 移除的区别
这里需要注意的是: 如果使用 git rm 文件 方式删除文件,删除操作是已经处在暂存区的;如果使用rm 文件 操作删除的话,该操作并不在Git的暂存区,若要提交变化,要先将改文件加入暂存区。
rm移除

git rm 移除

 然后就被移出掉了。 如果没有把移出变化提交我们可以回复文件的删除
恢复删除文件(未提交):git checkout – 文件

分支
Git仓库中各种分支的文件管理,可以极大程度提升文件立体管理。
创建分支:git checkout -b 新建分支名 切换分支:git checkout 分支名 查看分支:git branch 查看所有分支: git branch -a 更新分支代码并提交: git add * git commit -m “init newBranch” git push origin newBranch

连接远程库
使用Git可以连接Github、GitLab这样的一些远程仓库,由于本地仓库和远程仓库之间的数据传输是用SSH加密,所以再使用前应该先在远程仓库上添加本地Git的SSH密钥
查看SSH密钥:ssh-keygen -t rsa -C “youemail@example.com”
得到密钥后,再把SSH密钥粘贴至远程仓库  然后就可以在上面克隆你的本地版本库了。
Git命令大全
Git命令大全
|