您的位置:首页 > 其它

git快速入门之二:将远程仓库克隆到本地

2017-07-07 09:29 267 查看
首先来回顾一下,在上一篇git系列文章中,我们讲了如何创建本地git仓库并把文件push到远程仓库,也就是先有本地仓库,后有远程仓库。那么,这次我们来讲一个新的玩法,就是先有远程仓库,后有本地仓库,即把远程仓库“克隆(clone)”到本地。

假设现在你的团队其他成员已经在git上建好了仓库,并且也push过代码,这个远程git仓库还叫“StudyGit”,有两个文件:a.txt和README.md,现在,您也要开始贡献代码了,那么,您首先需要把团队其他成员提交的所有东西都拉取到你的本地目录,这个时候就会用到“clone”命令了:
git clone git@github.com:onlyanyz/StudyGit.git


只要执行这句指令,就可以把远程仓库的所有东西都拉取到本地工作目录了,当然生成的本地目录名和远程仓库名字是一样的。

如果您现在查看下当前本地git仓库的状态,如下:
yanyaozhen@macbookpro:~/Coding/StudyGit$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean


命令回显表示,我的本地分支已经更新为最新的远程master分支了。此后,我们就可以按照“git快速入门之一”这篇文章所述进行添加代码并提交了。

现在,让我们再看下刚才clone到本地的git项目,现在有两个文件,如下:
yanyaozhen@macbookpro:~/Coding/StudyGit$ ll
total 16
-rw-r--r--  1 yanyaozhen  staff    21B 11 19 00:04 README.md
-rw-r--r--  1 yanyaozhen  staff     4B 11 19 00:04 a.txt


接下来,假如A同学在github上的这个仓库中又新增了一个文件b.txt,那现在github远程仓库中就有三个文件(注意,现在本地仓库中的文件就已经与远程仓库不同了)。

接下来,我们在本地继续我们的开发工作,假如新建了一个文件“c.txt”,现在,让我们来把"c.txt"文件加入暂存区,然后commit到本地仓库,这时,我们想把刚才的工作成果再push到远程,执行如下:
yanyaozhen@macbookpro:~/Coding/StudyGit$ git push origin master
To git@github.com:onlyanyz/StudyGit.git
! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'git@github.com:onlyanyz/StudyGit.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.


阿欧,报错了,懂点英文的同学可以从提示信息看出问题所在,因为我们的远程已经有更新了,我们在push到远程的时候,必须先把远程的改动拉到本地合并起来,才能再次提交我的修改。所以,以下的命令就出场了:
$ git fetch origin master


该指令意思是从远程origin仓库的master主分支更新最新的版本到origin/master分支上。

然后我们比对下当前本地master分支和origin/master分支的区别:
$ git log -p master..origin/master


执行的回显结果会详细列出这两个分支的差异。

然后,我们需要把origin/master分支上的内容合并到本地master分支:
git merge origin/master


执行该指令后,可能会要求输入合并的理由,填写后,我们就合并成功了。这个时候,我们就可以再次push了:
yanyaozhen@macbookpro:~/Coding/StudyGit$ git push origin master
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (5/5), 543 bytes | 0 bytes/s, done.
Total 5 (delta 2), reused 0 (delta 0)
To git@github.com:onlyanyz/StudyGit.git
6b3662f..6036a05  master -> master


表示push成功,现在你可以去github上看到我们在本地新建的b.txt文件啦!

后记:有同学可能查了网上的资料,说“git fetch”和“git merge”指令可以合二为一,叫“git pull”,在此强烈建议大家使用分开的指令,因为“git pull”会直接合并,而不会等你确认,如果一旦合并错了,还是比较麻烦的。宁可慢一点,也别重头再来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐