Git常用命令 - merge vs. rebase

1. 配置

# 配置本仓库
git config --local
# 配置所有仓库
git config --global 
# 配置登陆用户所有的所有仓库
git config --system 

# 示例
git config --global user.name 'test'
git config --global user.email '[email protected]'

# 查看配置,可指定环境
git config --list --local/global/system

2. 初始化仓库

# 新建项目
git init new_project

# 已有项目
cd project
git init

3. 提交更改

# 添加文件到暂存区
git add file
# 添加目录
git add directory
# 组合
git add file1 file2 directory1 directory2
# 添加所有
git add .

# 提交
git commit -m '注释'

# 快捷方式:添加 + 提交
git commit -am '注释'

4. 查看日志

# 默认
git log 

# 简洁
git log --oneline

# 最近提交的5个日志 
git log -n5 

# 所有分支
git log --all

# 图形化
git log --graph

# 组合
git log --all --graph -n10 --oneline

5. 查看变更

# 有哪些变更
git status

# 工作区 vs. 暂存区
git diff
git diff -- file 

# 暂存区 vs. HEAD
git diff --cached

# 两个提交字间的对比
git diff commit1_hash commit2_hash

# 利用快捷方式
git diff HEAD HEAD^1
git diff HEAD HEAD~1

git diff HEAD HEAD^1^1
git diff HEAD HEAD~2

6. 回滚

# 将暂存区回滚到与HEAD一致
git reset HEAD
git reset HEAD -- file1 file2

# 将工作区回滚到与暂存区一致
git checkout 
git checkout -- file1 file2

# 回滚整个工作区和暂存区到HEAD
git reset HEAD --hard

# 回滚到某个提交
git reset hash --hard

7. 修改提交

# 修改最近一次提交的注释
git commit --amend

# 整理本地的commits,支持修改注释、合并提交等
git rebase -i 

8. 暂存

# 暂存,可执行多次
git stash

# 查看暂存了几次
git stash list 

# 应用暂存到当前工作区
git stash apply

# 应用暂存到当前工作区,并清除暂存
git stash pop

9. 远端仓库

# 尽量使用带协议的方式
git clone file:///path/top/repo.git
git clone https://git-server.com:port/path/to/repo.git 

# 不带工作区
git clone --bare file:///path/top/repo/.git rep.git

# 查看远程仓库
git remote -v

# 设置远程仓库
git remote add rep file:///path/top/repo.git

# 设置远端分支
git push --set-upstream 

# push branch and tags
git push remote --all
# push only tags
git push remote --tags 

# only fetch  
git fetch remote

# fetch and merge
git pull remote

10. 分支管理

# 创建并切换到新分支
git checkout -b new_branch
git checkout -b local_branch remote_branch

# 列出本地分支
git branch -v

# 包含远端分支
git branch -av

# 如果没有merge,会报错
git branch -d

# 强制删除
git branch -D

11. merge vs. rebase

11.1 merge

git.merge.png
# merge 流程
git checkout experiment
git merge master

11.2 rebase

git.rebase.png

提取在 C4 中引入的补丁和修改,然后在 C3 的基础上重新应用一次。
在 Git 中,这种操作就叫做 变基(rebase)。
如图,因为基线变了,所以叫 rebase 变基。

git checkout experiment
git rebase master

git checkout master
git merge experiment # 应为fast-forward

11.3 rebase的风险

不要再公共分支上(比如master)使用rebase,否则会遭到团队成员的唾弃!

因为,公共分支上的 变基,可能导致其他团队成员的不在公共分支上,从而导致代码重复合并。
看下图

git.rebase.risk.png

如果确实发生了,那就只能找到原因,然后用变基来解决变基

git.rebase.rebase.png

git checkout master
git pull --rebase

12. 其他

#查看类型
git cat-file -t hash
#查看内容
git cat-file -p hash

# 删除文件
git rm file
# 重命名文件
git mv file1 file2

# 强行push,慎用
git push -f remote branch

你可能感兴趣的:(Git常用命令 - merge vs. rebase)