概览:
安装Git
确认安装是否成功:
- Git:
1 | git --version |
我的版本:
1 | $ git --version |
出现版本号,说明安装成功。
下载后需要注册Github账号。
配置
生成SSH key以免密码加密访问github,
1 | ssh-keygen -t rsa -b 4096 -C "your_email@qq.com" |
打开文件C:/Users/Mardan/.ssh/id_rsa.pub,并复制文件里面的内容
进入https://github.com/settings/ssh,选择 new ssh key,粘贴刚刚复制的文件C:/Users/Mardan/.ssh/id_rsa.pub全部内容。
测试:
1 | ssh -T git@github.com |
输出:
1 | The authenticity of host ‘github.com (207.97.227.239)’ can’t be established. |
然后输入yes。
或
1 | Hi <your_username>! You've successfully authenticated, but GitHub does not provide shell access. |
说明已经链接github,如果没有,请重新来过。
初始设置
使用前请设置以下信息
1 | git config --global user.name "your_username" |
正式使用
进入工作目录(我的是 workspace),这个自己建立的,可以不一样的。
1 | cd workspace |
查看远程仓库地址
1 | $ git remote -v |
新建项目仓库:
…or create a new repository on the command line
1 | echo "# Learn Git" >> README.md |
使用已存在项目
…or push an existing repository from the command line
1 | git remote add origin <repo url> |
或者覆盖原远程仓库地址
1 | git remote set-url origin git@github.com:xxxxxxxx |
简单操作
git clone
然后克隆git仓库
1 | git clone <repo url> |
如若想克隆其他分支请用 -b
选项
like:克隆test分支。
1 | git clone -b test <repo url> |
git pull
拉取远程仓库代码
1 | $ git pull |
git push
同步本地仓库的提交和远程仓库的代码。
git status
基本已完成
分支管理
新建本地分支
1 | git branch <branch_name> |
查看该项目的所有本地和远程分支
1 | git branch -a |
切换本地分支
1 | git checkout <other branch_name> |
把远程分支的代码pull到本地分支
1 | git pull origin <branch_name> |
PS:push代码前最好先用pull更新本地代码。
第一次需要填写完整命令。
1 | git push -u origin master |
之后只要git push
就行了。
版本回退
查看修改记录
1 | git reflog |
回退至上一个版本
1 | git reset head HEAD^ |
撤回回退
1 | git reset --hard "id" |
子模块
如果项目包含子模块,需要添加参数--recursive
1 | git clone <repo url> --recursive |
问题解决
文件冲突
第一次上传有可能会遇到push失败的情况,那是因为跟SVN一样,github上有一个README.md 文件没有下载下来 。我们得先
1 | git pull --rebase origin master |
然后执行
1 | git push -u origin master |
就可以成功啦。
强制合并
如果想强制覆盖远程仓库,可以采用–force参数,(除非仓库禁止强制覆盖提交)。
1 | git push --force |
版本冲突解决
Github上面的一个仓库很久没有更新了,最近想写点新的东西放上去。结果提示:master and dev are entirely different commit histories.两个分支是两个不同的版本,具有不同的提交历史,想要拉取和提交都被拒绝,找了资料和百度,发现要加一句命令才可以,记下备忘。解决方案如下:
1 | git checkout master #切换到要提交代码的分支 |
NOTE:首先需要pull,发现refusing to merge unrelated histories,因为两个仓库提交历史不一致,无法pull拉取远程信息,所以需要在GIT命令中添加一句代码:–allow-unrelated-histories允许不相关历史进行提交,代码是在git 2.9.2版本发生的,最新的版本需要添加–allow-unrelated-histories (eg:git pull origin master --allow-unrelated-histories)