1. 本地库推送到远程库
本地库关联远程仓库,origin只是一个自定义远端的名称,也可以自定义别的名称
git remote add origin git@github.com:michaelliao/learngit.git
本地库推送代码到远程仓库
-
远程仓库是空的
由于远程库是空的,我们第一次推送master分支时,加上了-u参数,Git不但会把本地的master分支内容推送的远程新的master分支,还会把本地的master分支和远程的master分支关联起来,在以后的推送或者拉取时就可以简化命令。git push -u origin master
遇到如下错误提示
error: src refspec master does not match any.
error: failed to push some refs to 'git@github.com/demo.git'
需要先 git add ./
再执行 git commit -m “首次提交”
后执行 git push origin master
推送本地所有分支到远程库
git push origin --all
- 远程仓库非空:(比如你gitlab新建项目时创建了一个README.md文件)
此时你无法正常提交:会提示 “Note about fast-forwards”
To github.com:zwkkkk1/chatroom.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:zwkkkk1/chatroom.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
原因是远程和本地都有各自的commit,而两者之间没有共同的commit历史,无法合并,解决方案:
git pull origin master --allow-unrelated-histories
又出错了
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.
git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream-to=origin/<branch> master
原因是没有指定本地 master 分支和远程 origin/master 的连接,这里根据提示:
git branch --set-upstream-to=origin/master master
产生冲突,这里的README.md就是前面提到的远程仓库的文件,需要合并冲突
$ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add <file>..." to mark resolution)
both added: **README.md**
no changes added to commit (use "git add" and/or "git commit -a")
git add README.md
git commit -a
git push
2. 从远程库克隆到本地
Git支持多种协议,包括https,但通过ssh支持的原生git协议速度最快
git clone git@github.com/demo.git []
git clone git@github.com:michaelliao/gitskills.git
取消本地与远程的关联
git remote remove origin
3. 只做备份 从远端备份到本地
–bare的作用是建立不带工作区的裸仓库,方便后期直接pull
git clone --bare https://github.com/Demo.git backup.git
4. fetch和pull
fetch:将远程分支拉取不与本地分支关联
pull:分为两步 先fetch操作 再合并本地分支
$ git fetch github master
$ gitk --all
总结:以下两条命令等效
git pull origin dev
git fetch origin dev
git merge origin/dev