说明

此篇文章记录在日常 coding 的操作以及一些必要的 git 概念

git 的初始化设置

1
2
git config --global user.name "Your Name"
git config --global user.email "[email protected]"

config 的三个作用域,缺省等同于local

1
2
3
git config --local ## local只对某个仓库有效
git config --global ## global对当前用户所有仓库有效
git config --system ## system对系统所有登录的用户有效

显示 config 的配置,加--list

1
2
3
git config --list --local ## local只对某个仓库有效
git config --list --global ## global对当前用户所有仓库有效
git config --list --system ## system对系统所有登录的用户有效

查看提交记录

1
git log --oneline

image-20220305220137649

1
git log -n2 --oneline

n2 表示所有分支最近两个。

image-20220305220229829

1
git log

image-20220305220412495

1
git log --all

提交记录

修改 commit 的 message

此操作不建议对已发布到线上的 commit 做修改。

1
git commit --amend

image-20220305222413228

修改老旧 commit 的 message,需要使用其上一个 commitId。

1
git reabase -i commitId

image-20220305222826712

image-20220305223007339

在新窗口中重新编辑 commit 信息即可。

image-20220305223056685

将多个 commit 整理成一个 commit

1
2
git rebase -i commit的父哈希值
# 然后将需要合并的改为s。

image-20220305223844839

将除第一个外需要合并的修改为s即可进行编辑信息。

1
git rebase -i commit的父哈希值

进入编辑页面后,将需要合并的写在一起。如果没有自动出现则手动键入即可。需要删除的使用s命令,保留的使用pick

image-20220305224945894

image-20220305225107076

接下来编辑 commit 信息即可。

  • pick:保留该 commit(缩写:p)
  • reword:保留该 commit,但我需要修改该 commit 的注释(缩写:r)
  • edit:保留该 commit, 但我要停下来修改该提交(不仅仅修改注释)(缩写:e)
  • squash:将该 commit 和前一个 commit 合并(缩写:s)
  • fixup:将该 commit 和前一个 commit 合并,但我不要保留该提交的注释信息(缩写:f)
  • exec:执行 shell 命令(缩写:x)
  • drop:我要丢弃该 commit(缩写:d)

操作暂存区和工作区

恢复文件变更

  1. 编辑了某文件,但想放弃修改,恢复至与暂存区一致
1
git checkout 文件名

恢复暂存区

1
git reset HEAD
1
git reset HEAD -- fileName1 fileName2

分支操作

查看分支

1
git branch
1
git branch -r
1
git branch -a

新建分支

1
git branch [branch-name]
1
git checkout -b [branch]
1
git checkout -b [branch]
1
git checkout -b [branch] [tag]
1
git branch --track [branch] [remote-branch]
1
git branch --track [branch] [remote-branch]

切换分支

1
git checkout [branch-name]
1
git checkout -
1
git checkout -b [branch]

代码合并

选择几个 commit

此操作建议将最底层开始选择,例如:git cherry-pick A B,其中 A 的提交必须早于 B 的提交。

1
git cherry-pick <commitHash>

转移连续的提交 A 到 B,并且包含 A

1
git cherry-pick A^..B

merge 合并

此合并方式会生成一个新的 commit 信息

1
git merge <branchName>

标签

查看 tag

1
git tag
1
git show <tagName>

新建 tag

1
git tag <tagName>
1
git tag <tagName> <commitId>

删除 tag

1
git tag -d [tag]
1
git push origin :refs/tags/[tag]

提交 tag

1
git push [remote] --tags
1
git push [remote] [tag]

常见场景

开发中临时加塞了紧急任务

1
2
3
4
5
6
7
8
# 将当前状态暂存起来
git stash
# 将之前的暂存信息弹出来,并会保存暂存队列
git stash apply
# 将之前的暂存信息弹出来,不保存暂存队列
git stash pop
# 查看暂存队列
git stash list

常用命令脑图

git