1安装
下载地址:https://git-scm.com/downloads
linux:
apt-get install git
yum install git
mac:
AppStore中Xcode有集成git,Xcode-Preferences-Downloads-Command Line Tools-Install
2创建,克隆,提交,回滚
创建仓库:在当前路径下执行:git init
设置配置:
$ git config --global user.name 'runoob'
$ git config --global user.email test@runoob.com
克隆:git clone <repo> <directory>
添加文件:git add <file>
删除文件:git rm <file>
提交文件:git commit -m "<message>"
跳过ADD过程提交:git commit -a
查看状态:git status
查看变化:git diff
显示资源历史:git log --pretty==oneline
回滚到指定版本:git reset --hard versionid (前4位即可)
历史命令:git reflog
3工作区、暂存区和版本库
- 工作区:就是你在电脑里能看到的目录。
- 暂存区:英文叫stage, 或index。一般存放在 ".git目录下" 下的index文件(.git/index)中,所以我们把暂存区有时也叫作索引(index)。
- 版本库:工作区有一个隐藏目录.git,这个不算工作区,而是Git的版本库。
git checkout -- <file>:让这个文件回到最近一次git commit
或git add
时的状态
git reset HEAD <file>:版本库替换暂存区
git checkout HEAD <file>:版本库替换暂存区和工作区
4远程仓库,GitHub
4.1设置SSH加密
第1步:创建SSH Key。在用户主目录(如C:\Users\Administrator)下,看看有没有.ssh目录,如果有,再看看这个目录下有没有id_rsa
和id_rsa.pub
这两个文件,如果已经有了,可直接跳到下一步。如果没有,打开Shell(Windows下打开Git Bash),创建SSH Key:
$ ssh-keygen -t rsa -C "youremail@example.com"
你需要把邮件地址换成你自己的邮件地址,然后一路回车,使用默认值即可,也无需设置密码。
如果一切顺利的话,可以在用户主目录里找到.ssh
目录,里面有id_rsa
和id_rsa.pub
两个文件,这两个就是SSH Key的秘钥对,id_rsa
是私钥,不能泄露出去,id_rsa.pub
是公钥,可以放心地告诉任何人。
第2步:登陆GitHub,打开“Account settings”,“SSH Keys”页面
然后,点“Add SSH Key”,填上任意Title,在Key文本框里粘贴id_rsa.pub
文件的内容
点“Add Key”,你就应该看到已经添加的Key
假定你有若干电脑,你一会儿在公司提交,一会儿在家里提交,只要把每台电脑的Key都添加到GitHub,就可以在每台电脑上往GitHub推送了。
4.2创建远程仓库,并关联本地仓库
界面右上角找new reporitory,执行创建远程仓库
按提示创建本地仓库或直接绑定本地仓库
1、create a new repository on the command line
echo "# gof" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/qqchaozai/gof.git
git push -u origin master
2、push an existing repository from the command line
git remote add origin https://github.com/qqchaozai/gof.git
git push -u origin master
由于远程库是空的,第一次推送master
分支时,加上了-u
参数,Git不但会把本地的master
分支内容推送的远程新的master
分支,还会把本地的master
分支和远程的master
分支关联起来,在以后的推送或者拉取时就可以简化命令。
git fetch:从远程获取最新版本到本地,不会自动merge
git pull:从远程获取最新版本并merge到本地
git push:推送本地版本到远程版本库
5分支管理
查看分支:git branch
创建分支:git branch <name>
切换分支:git checkout <name>
创建+切换分支:git checkout -b <name>
合并某分支到当前分支:git merge <name>
删除分支:git branch -d <name>
分支回退:git reset --hard a002085eabddf7041d7b999abd49d1bd234ae33a
本地强制提交:git push origin dev-stable-01 --force
6异常
1、You have not concluded your merge (MERGE_HEAD exists). Please, commit your changes before you can merge.
可能原因:以前pull下来的代码没有自动合并导致的
解决办法一:保留本地的更改,中止合并->重新合并->重新拉取
$:git merge --abort
$:git reset --merge
$:git pull
$:git fetch --all
$:git reset --hard origin/master
$:git fetch
爱家人,爱生活,爱设计,爱编程,拥抱精彩人生!