Git 速查清单

本文最后更新于:2023年9月1日 上午

记录一些最常用的命令(从上往下使用频率依次降低),当然,这里只是吾辈个人的,其他功能可能暂时还没用到呢

详细的 git 相关知识强烈推荐 Pro Git

基本命令

关键词 命令格式 命令解释 命令示例
init git init 为当前目录初始化 git 本地仓库
add git add [要追踪的文件/路径] 添加到 git 跟踪 git add -A
commit git commit [路径] [选项] [提交说明] 提交当前的修改内容 git commit -a -m "提交全部的修改"
remote git remote [选项] [远程仓库名] 操作 git 远程仓库 git remote
git remote add origin https://github.com/rxliuli/rxliuli.github.io.git
git remote show origin
git remote remove origin
push git push [远程别名] [远程分支] 推送本地修改到远程 git push origin master
pull git pull [远程别名] [远程分支] 拉取远程修改到本地 git pull origin master
status git status 查看本地仓库的状态,以此得知添加和修改的文件
clone git clone [远程仓库地址] 克隆一个远程仓库到本地,这里和 pull 不同点在于本地不存在要克隆的仓库 git clone https://github.com/rxliuli/rxliuli.github.io.git
log git log [选项] 查看 git 日志 git log
revert git revert [提交记录 hash] 撤销掉指定提交 git revert ab1c2d2
reset git reset [提交记录 hash] 重置到某次提交上,和上面不一样的是不会添加新的提交记录,而是删除已有的提交记录 git reset ab1c2d2
git reset HEAD~[N 回退次数] 回退最近几次的提交, N 为几就回退几次 git reset HEAD~1
branch git branch [分支] git 分支(强大而又复杂的功能) git branch dev
git branch
git branch dev -D
checkout git checkout [分支名] 切换当前分支(分支之间不共享修改) git checkout master
git checkout origin/dev -b dev
merge git merge [选项] 合并其他分支的修改到当前分支上 git merge dev
git merge origin/master --allow-unrelated-histories
push git push [远程仓库名] :[分支名] 删除掉指定的远程分支(仓库还在,只是删除分支) git push origin :dev
stash git stash 暂存本地更改
git stash list 查看所有暂存更改
git stash apply [index] 重新应用指定暂存更改 git stash apply
git stash drop [index] 删除掉指定的暂存更改 git stash drop

复合命令

撤销掉本地所有的修改

命令

1
git add -A && git stash && git stash drop

解释

  1. 添加所有更改到 git 追踪中(如果没有被忽略的话)
  2. 添加所有本地更改到暂存区域中
  3. 删除掉刚添加的最新暂存更改

应用场景修改了一些文件但又没有提交,突然发现有问题,想把它们全删除了重来,或者全部回到上次提交,先把这些修改暂存起来(不加最后一条命令)

区分文件名大小写

命令

1
git config core.ignorecase false

解释 Windows 下默认不区分文件名大小写,所以需要特别设置一下。

git push 强制推送

命令

1
git push -f

解释

强制推送到远程分支,即便是远程包含本地不存在的提交

忽略已经跟踪的文件的提交

参考:怎样让 Git 忽略当前已经更改的文件

忽略修改

1
git update-index --assume-unchanged <files>

取消这种设定

1
git update-index --no-assume-unchanged <files>

从远端拉取分支

参考:git 获取远程服务器的指定分支

命令

1
git checkout -b [本地分支名(不存在)] [远程分支名]

示例

1
git checkout -b dev origin/dev

忽略已提交的文件修改

参考:git 如何忽略已经提交的文件 (.gitignore 文件无效)

主要用于忽略一些本地修改的文件但又不希望提交,同时也不希望添加到 .gitignore 中将之从云端排除的方式。

1
git update-index --assume-unchanged [file-pattern]

git 删除远程 tag

显示本地 tag

1
git tag

删除本地 tag

1
git tag -d Remote_Systems_Operation

用 push, 删除远程 tag

1
git push origin :refs/tags/Remote_Systems_Operation

删除远程分支

1
2
git branch -r -d origin/branch-name
git push origin :branch-name

两个 git 仓库合并

现在有两个仓库 kktjs/kktkktjs/kkt-next 我们需要将 kkt-next 仓库合并到 kkt 并保留 kkt-next 的所有提交内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 1. 克隆主仓库代码
git clone [email protected]:kktjs/kkt.git

# 2. 将 kkt-next 作为远程仓库,添加到 kkt 中,设置别名为 other
git remote add other [email protected]:kktjs/kkt-next.git

# 3. 从 kkt-next 仓库中拉取数据到本仓库
git fetch other

# 4. 将 kkt-next 仓库拉取的 master 分支作为新分支 checkout 到本地,新分支名设定为 dev
git checkout -b dev other/master

# 5. 切换回 kkt 的 master 分支
git checkout master

# 6. 将 dev 合并入 kkt 的 master 分支
git merge dev

# 如果第 6 步报错 `fatal: refusing to merge unrelated histories`
# 请执行下面命令 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
git merge dev --allow-unrelated-histories

JetBrains IDE 提供了非常好用的冲突合并工具

在合并时有可能两个分支对同一个文件都做了修改,这时需要解决冲突,对文本文件来说很简单,根据需要对冲突的位置进行处理就可以。对于二进制文件,需要用到如下命令:

1
2
3
git checkout --theirs YOUR_BINARY_FILES     # 保留需要合并进来的分支的修改
git checkout --ours YOUR_BINARY_FILES # 保留自己的修改
git add YOUR_BINARY_FILES

参考: https://segmentfault.com/a/1190000021919753

在 git 目录中忽略 git 子模块的所有变更

参考 git submodule

1
2
3
4
5
# .gitmodules
[submodule "examples/blog-hexo-example/themes/next"]
path = examples/blog-hexo-example/themes/next
url = https://github.com/theme-next/hexo-theme-next
ignore = all

git 提交时忽略 hooks

添加 --no-verify 参数即可

1
git commit --no-verify

Git 错误 Reset 恢复

  1. 找到使用 git reset 之前的最后一次提交的 commit id

    1
    2
    # 查看 git 记录的所有操作,包括回退操作也会记录
    git reflog
  2. 使用 git reset --hard 回退

    1
    2
    # 回退到指定提交,但不会将之后提交混入到未提交的内容
    git reset --hard dd256c7d66ad2e9671cbd47650ffddc4267ca7d5
  3. 使用 git log 检查最后一次提交是否恢复

    1
    2
    # 这时可以看到最后一次提交已经恢复了
    git log

参考: 执行了 git reset,还有办法取消吗?

Git 高级合并

前端想要调整项目组织将之前的项目放到 monorepo 中,所以需要使用 git 将之前的项目合并到新项目的指定目录中,同时保留所有记录。

主要依赖功能 高级合并 => 子树合并,同时参考错误解决方案 The “fatal: refusing to merge unrelated histories” Git error

1
2
3
4
5
6
git remote add rack_remote https://github.com/rack/rack
git fetch rack_remote --no-tags
git checkout -b rack_branch rack_remote/master
git checkout master
git read-tree --prefix=rack/ -u rack_branch
git merge --squash -s recursive -Xsubtree=rack rack_branch --allow-unrelated-histories

系统更新后 git 错误

需要修改 ~/.ssh/config 配置文件

1
2
3
4
Host *
ServerAliveInterval 10
HostKeyAlgorithms +ssh-rsa
PubkeyAcceptedKeyTypes +ssh-rsa

关联本地与远端分支

当你 git push 时可能会提示需要关联,基本上复制提示的命令即可。下面是关联本地与远端的 master 分支的方法

1
git push --set-upstream origin master

之后便可以直接 git push 推送代码了

git log 设置日期格式

默认 git log 使用的日期格式对于国内并不方面查看,但 git 支持设置格式化格式。

1
git config --global log.date format:"%Y-%m-%d %H:%M:%S"

参考:Git log 修改时间格式

查看指定目录的 commit 历史

jetbrains ide 自带,但 vscode 没有,所以需要用命令行。。。

1
git log --oneline .

Windows 下配置避免中文乱码

在公司的电脑上碰到了 Git 中文乱码的问题,例如想要查看一下仓库的状态,中文全部变成了 umber 的形式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)

modified: "source/_posts/JavaScript/\345\234\250\344\274\240\347\273\237\351\241\271\347\233\256\344\270\255\344\275\277\347\224\250-babel-\347\274\226\350\257\221-ES6.md"
modified: "source/_posts/Tool/IDEA/IDEA \344\275\277\347\224\250\346\212\200\345\267\247.md"
modified: test/test.html
modified: test/test.js

no changes added to commit (use "git add" and/or "git commit -a")

解决方案

该方案摘抄自 解决 Git 在 windows 下中文乱码的问题

配置一下这些内容即可

1
2
3
4
5
git config --global core.quotepath false # 显示 status 编码
git config --global gui.encoding utf-8 # 图形界面编码
git config --global i18n.commit.encoding utf-8 # 提交信息编码
git config --global i18n.logoutputencoding utf-8 # 输出 log 编码
export LESSCHARSET=utf-8 # 最后一条命令是因为 git log 默认使用 less 分页,所以需要 bash 对 less 命令进行 utf-8 编码

git log 选项

  • --format: 设置格式,例如 %s 可以仅显示提交的消息
  • --author: 根据提交者过滤
  • --no-merges: 过滤掉合并的历史
  • --reverse: 反转排序,按照时间正序
  • --max-count: 显示的 commit 最大数量
  • --after: 显示指定日期之后的 commit
1
git log --format="%s %cd" --no-merges --author=rxliuli --after=2022-01-01 --reverse --max-count=10

获取文件在指定时间后的内容

获取文件在指定日期后面的第一次提交

1
git log --after=2022-07-01 --max-count=1 -- ./package.json

获取文件在特定提交时的内容

1
git show 0e120d21e7376268ebd0b574bee2b923f2b9fd34:./package.json

使用 js(simple-git)获取的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const git = simpleGit()

async function getFileAfter(
filePath: string,
date: Date,
): Promise<string | null> {
const after = await git.log({
file: filePath,
maxCount: 1,
'--after': date.toISOString(),
})
if (!after.latest) {
return null
}
await git.cwd(path.dirname(filePath))
const stat = await git.show(`${after.latest.hash}:${path.basename(filePath)}`)
return stat
}

删除所有被 gitignore 忽略的文件

有时候会需要清理当前项目到刚刚 clone 的状态以便清理掉各种缓存问题。

1
2
git clean -xdn
git clean -xdf

不过清理项目的缓存更好的方式是结合上 find 命令

1
2
3
find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;
git add -A && git stash
git clean -xdf

ref: https://stackoverflow.com/a/36573710

换行符警告

在 Windows 上使用 git 会出现警告 LF will be replaced by CRLF the next time Git touches it,适用以下全局配置即可

1
git config --global core.autocrlf false

ref: https://stackoverflow.com/a/17628353

合并特定分支的指定提交

使用 git cherry-pick 即可

1
git cherry-pick 743a35e2f1b9400658e04f7a2724eecf063901b6

ref: https://lonelyrookie.github.io/2019/06/30/Git%E5%90%88%E5%B9%B6%E7%89%B9%E5%AE%9Acommits%E5%88%B0%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%88%86%E6%94%AF/

创建空的分支

1
2
3
git switch --orphan <new branch>
git commit --allow-empty -m "Initial commit on orphan branch"
git push -u origin <new branch>

ref: https://stackoverflow.com/questions/34100048/

检查被删除文件的 log

有时候文件被错误的删除了,需要知道被删除的文件的历史记录,可以使用以下命令

如果不知道具体的路径可以使用 glob 匹配

1
git log --all --full-history -- "**/thefile.*"

如果知道具体路径则可以直接指定

1
git log --all --full-history -- <path-to-file>

ref: https://stackoverflow.com/questions/7203515/

问题:如何查看特定文件的历史呢?即使现在这个文件已经被删除了?

git pull 拉取代码时自动合并

如果可能,让 git 自动合并并提交 commit 即可,不需要无谓的确认。

git config –global –edit 设置 vscode 作为默认编辑器

要将 VS Code 设置为 Git 的全局配置文件编辑器,您需要执行以下步骤:

打开 VS Code 并安装 Shell Command: Install ‘code’ command in PATH,这将添加 “code” 命令到终端。

打开终端并输入以下命令:

1
git config --global core.editor "code --wait"

这将告诉 Git 使用 VS Code 作为全局编辑器,并且在编辑完文件并关闭 VS Code 后等待 Git 继续执行。

确认设置已生效。您可以通过运行以下命令来检查全局配置:

1
git config --global core.editor

如果您看到输出是 “code –wait”,那么您已成功将 VS Code 设置为 Git 的全局配置文件编辑器。

现在,每当您需要编辑 Git 的全局配置文件时,Git 将自动打开 VS Code 编辑器。

该答案来自 chatgpt

git 手动合并之后如何提交

解决完冲突后运行以下命令继续合并即可

1
git merge --continue

创建和应用 patch

为当前 staged change 创建 patch

1
git diff --cached > my_changes.patch

合并 patch

1
git apply my_changes.patch

创建 tag 并推送到远端

例如

1
2
3
4
5
6
# 清理本地和远端的 tag
git tag -d v0.1.0
git push origin :refs/tags/v0.1.0
# 创建新的推送到远端
git tag -a v0.1.0 -m "Release version 0.1.0"
git push origin v0.1.0

Git 速查清单
https://blog.rxliuli.com/p/b63ba6ff31c049f8a6703ce7022a79e6/
作者
rxliuli
发布于
2020年2月2日
许可协议