Git
准备工作
安装
-
Ubuntu
- sudo apt-get install git
-
Windows
-
下载、安装
- https://git-scm.com/downloads
-
全局配置
- git config --global user.name “Your Name”
- git config --global user.email “email@example.com”
创建版本库
-
初始化一个Git仓库
- git init
-
添加文件到Git仓库
- git add
- git commit -m “message”
版本控制
版本回退
-
查看提交历史
- git log
-
在版本的历史之间穿梭
- git reset --hard commit_id
-
重返未来
-
查看历史命令
- git reflog
-
工作区、暂存区
撤销修改
-
改乱了工作区某文件,想直接丢弃工作区的修改
- git checkout – file
-
改乱了工作区某文件,还添加到了暂存区时,想丢弃修改
- git reset HEAD
- git checkout – file
-
已经提交了不合适的修改到版本库时,想要撤销本次提交
删除文件
-
删除工作区文件
- rm
-
删除暂存区文件
- git rm
-
提交删除
- git commit -m “remove file”
远程仓库
添加远程github库
-
在github上建立一个库
-
关联远程库
- git remote add origin git@github.com:account-name/repo-name.git
-
首次 推送
- git push -u origin master
-
常规推送
- git push origin master
从远程库克隆
-
ssh
- git clone git@github.com:account-name/repo-name.git
-
https
- git clone https://github.com/account-name/repo-name.git
使用GitHub
- 在GitHub上,可以任意Fork开源仓库
- 自己拥有Fork后的仓库的读写权限
- 可以推送pull request给官方仓库来贡献代码
使用gitee远程库
-
在码云上建立一个库
-
查看远程库信息
- git remote -v
-
删除已有的GitHub远程库
- git remote rm origin
-
关联码云的远程库
- git remote add origin git@gitee.com:account-name/repo-name.git
同时关联github和码云
- git remote add hub_origin git@github.com:account-name/repo-name.git
- git remote add ee_origin git@gitee.com:account-name/repo-name.git
分支管理
创建、合并
-
查看分支
- git branch
-
创建分支
- git branch
-
切换分支
- git checkout 或者git switch
-
创建+切换
- git checkout -b 或者git switch -c
-
合并某分支到当前分支
- git merge
-
删除分支
- git branch -d
解决冲突
- 冲突:master分支和feature1分支各自都对同一个文件分别有新的提交
- 在后提交的分支上手动修改冲突文件
- 再git add 、git commit
分支管理策略
-
再merge分支时,生成一个commit
- git merge --no-ff -m “merge with no-ff” dev
-
master分支、发布新版本、不干活
-
dev分支干活
- 完事后merge到master
-
团队合作时,每个人都往dev分支上合并
bug分支
-
修复bug时,创建新的bug分支进行修复,然后合并,最后删除
-
当手头工作没有完成时,先把工作现场git stash
-
修复bug后,再git stash pop
-
在master分支上修复的bug,想要合并到当前dev分支
- git cherry-pick
feature分支
-
开发一个新feature,最好新建一个分支
-
丢弃未合并过的分支
- git branch -D
多人协作
-
从本地推送分支,使用git push origin branch-name,如果推送失败,先用git pull抓取远程的新提交
-
在本地创建和远程分支对应的分支
- git checkout -b branch-name origin/branch-name
-
建立本地分支和远程分支的关联
- git branch --set-upstream branch-name origin/branch-name
-
从远程抓取分支,使用git pull,如果有冲突,要先处理冲突。
rebase
- rebase操作可以把本地未push的分叉提交历史整理成直线
- 使得查看历史提交的变化时更容易
标签管理
创建标签
-
新建一个标签,默认为HEAD
- git tag
-
为指定commit id新建标签
- git tag
-
指定标签信息
- git tag -a -m “blablabla…”
-
查看说明文字
- git show
-
查看所有标签
- git tag
-
查看指定标签
- git tag
操作标签
-
推送一个本地标签
- git push origin
-
推送全部未推送过的本地标签
- git push origin --tags
-
删除一个本地标签
- git tag -d
-
删除一个远程标签
- git push origin :refs/tags/
自定义
忽略特殊文件
配置别名
alias | realname |
---|---|
lg | log --color --graph --pretty=format:’%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset’ --abbrev-commit |
st | status |
co | checkout |
ci | commit |
br | branch |
unstage | reset HEAD |
last | log -1 |