# Git Cheatsheet

Created on Fri, 03 Jan 2020, 05:20PM

Last changed on Fri, 03 Jan 2020, 05:20PM

​ 之前用`git` 的时候时不时会遇到一些非`add, commit, push`的情况，也查过不少相关的高级用法，但往往就用一次之后就忘记了，最近看了篇[文章](https://dev.to/maxpou/git-cheat-sheet-advanced-3a17)，顺着这篇文章也捋一下`git`的高级用法以备后用。

## 不那么高级却很有用的Tips

* `git log --oneline` # 简介明了的git日志, 一行就很明了的日志打印形式
* `git checkout -` # 回到切换分支之前的分支, 类似于`cd -` 切换回之前的工作目录
* `git log --all --grep='homepage'` # 在所有提交日志中搜索包含「homepage」的提交
* `git log --author="Maxence"` # 获取某人的提交日志
* `git commit --amend -m "更新后的提交日志"` # 编辑上次提交的message
* `git add . && git commit --amend --no-edit` # 在上次提交中附加一些内容，保持提交日志不变
* `git commit --allow-empty -m "chore: re-trigger build"` # 空提交 —— 可以用来重新触发 CI 构建
* `git reflog` # 获取所有操作历史
* `git reset HEAD@{4}` # 重置到相应提交
* `git reset --hard <'commit-hash'>` # ……或者……
* `git diff master..my-branch`
* `git fetch origin`
* `git checkout master`
* `git reset --hard origin/master`

## Advanced cheat sheet

### squash 提交

比方说我想要 rebase 最近 3 个提交：

1. `git rebase -i HEAD~3`
2. 保留第一行的 `pick`，剩余提交替换为 `squash` 或 `s`
3. 清理提交日志并保存（vi 编辑器中键入 `:wq` 即可保存）

```git
pick 64d26a1 feat: add index.js
s 45f0259 fix: update index.js
s 8b15b0a fix: typo in index.js
```

### Fixes

比方说想在提交 `fed14a4c` 加上一些内容。

```
git add .

git commit --fixup HEAD~1
# 或者也可以用提交的哈希值（fed14a4c）替换 HEAD~1

git rebase -i HEAD~3 --autosquash
# 保存并退出文件（VI 中输入 `:wq`）
```

...未完待续...

## Reference

\[1] [git 高级用法小抄](https://nextfe.com/git-cheatsheet-advanced/)

\[2] [Git: Cheat Sheet (advanced)](https://dev.to/maxpou/git-cheat-sheet-advanced-3a17)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.junyangz.com/note/git-cheatsheet-advanced.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
