在Github创建远程仓库
在将本地的内容推送到Github之前需要在Github上完成注册并创建一个仓库用于存放推送的内容。
通过Github完成注册以后即可登录创建仓库: 点击New repository并填入repository的信息: 远程仓库就创建成功了。
获取远程仓库地址
在Github远程仓库点击Code选项即可获取远程仓库的地址
Git连接远程仓库并推送内容
在项目文件夹初始化仓库
git init
在Git中创建远程仓库地址变量
git remote add xxx(var for remote repository )
$ git remote add rep https://github.com/***/DevRep.git
$ git remote -v
rep https://github.com/***/DevRep.git (fetch)
rep https://github.com/***/DevRep.git (push)
创建并提交测试文件test.txt
vim test.txt
git add test.txt
git commit -m "Initial commit test"
将本地仓库内容推送至远程仓库
git push rep master
之后,便可以在Github远程仓库上看到推送的内容。
克隆远程库到本地库
创建一个新的文件夹,在文件夹中点击鼠标右键,通过Git Bash Here打开Git命令行工具,键入以下指令即可完成克隆。
$ git clone https://github.com/***/DevRep.git
Cloning into 'DevRep'...
git clone指令完成的操作:
-
将远程库克隆到本地库 -
完成本地库的初始化 -
创建origin远程仓库地址变量
$ git remote -v
origin https://github.com/***/DevRep.git (fetch)
origin https://github.com/***/DevRep.git (push)
拉取远程库的修改
如果团队里的其他人已经将内容推送到了远程库,我们就需要先将远程库中的修改拉取到本地库,才能继续进行推送操作。
拉取操作的指令:
git pull [remote repository variable name][remote branch name]
在Github远程库修改测试文件如下:
$ git pull origin master
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/***/DevRep
* branch master -> FETCH_HEAD
575da76..7ac7828 master -> origin/master
Updating 575da76..7ac7828
Fast-forward
test.txt | 1 +
1 file changed, 1 insertion(+)
在本地库当前分支查看测试文件
$ cat test.txt
Hello world!
Hello, Hello!
git pull指令完成的操作:
- git fetch [remote repository variable name][remote branch name]
作用: 将远程库下载到本地,但未和本地库合并,下载的内容存放在[remote repository variable name]/[remote branch name]分支里
在Github远程仓库修改测试文件如下:
$ git fetch origin master
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Total 3 (delta 0), reused 2 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/***/DevRep
* branch master -> FETCH_HEAD
97892a4..575da76 master -> origin/master
直接在本地库当前分支查看测试文件,修改内容还未合并到此文件
$ cat test.txt
Hello world!
Hello Github!
切换到origin/master分支,再查看测试文件,修改内容已下载到本地
$ git checkout origin/master
Note: checking out 'origin/master'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b <new-branch-name>
HEAD is now at 575da76... Update test.txt
$ cat test.txt
Hello world!
- git merge [remote repository variable name]/[remote branch name]
作用: 将下载的远程库的内容合并到本地库
切换回本地库的master分支,进行合并操作,再查看测试文件,可以看到修改已经同步到本地库
$ git merge origin/master
Updating 97892a4..575da76
Fast-forward
test.txt | 1 -
1 file changed, 1 deletion(-)
$ cat test.txt
Hello world!
|