Git 备忘单

入门

开始一个新仓库

git init

克隆现有仓库

git clone <url>

准备提交

添加未跟踪文件或未暂存的更改

git add <file>

添加所有未跟踪文件和未暂存的更改

git add .

选择文件中要暂存的部分

git add -p

移动文件

git mv <old> <new>

删除文件

git rm <file>

让 Git 忽略文件但不删除它

git rm --cached <file>

取消暂存单个文件

git reset <file>

取消暂存所有内容

git reset

检查添加了什么

git status

执行提交

创建一个提交(并打开文本编辑器编写消息)

git commit

创建一个提交

git commit -m 'message'

提交所有未暂存的更改

git commit -am 'message'

比较暂存区/工作区差异 (Diff)

比较所有暂存和未暂存的更改

git diff HEAD

仅比较已暂存的更改

git diff --staged

仅比较未暂存的更改

git diff

比较提交间差异 (Diff)

显示提交与其父提交之间的差异

git show <commit>

比较两个提交

git diff <commit> <commit>

比较自某个提交以来的单个文件

git diff <commit> <file>

显示差异摘要

git diff <commit> --stat git show <commit> --stat

丢弃更改

删除单个文件的未暂存更改

git restore <file> git checkout <file>

删除单个文件的所有已暂存和未暂存更改

git restore --staged --worktree <file> git checkout HEAD <file>

删除所有已暂存和未暂存的更改

git reset --hard

删除未跟踪的文件

git clean

“贮藏 (Stash)”所有已暂存和未暂存的更改

git stash

代码考古

查看分支历史

git log main git log --graph main git log --oneline

显示修改过某个文件的所有提交

git log <file>

显示修改过某个文件的所有提交,包括重命名之前

git log --follow <file>

查找所有添加或删除过某些文本的提交

git log -G banana

显示文件中每一行最后是谁修改的

git blame <file>

恢复旧文件

获取另一个提交中的文件版本

git checkout <commit> <file> git restore <file> --source <commit>

添加远程仓库

git remote add <name> <url>

拉取更改

获取更改(但不改变任何本地分支)

git fetch origin main

获取更改并变基 (Rebase) 你的当前分支

git pull --rebase

获取更改并将其合并 (Merge) 到你的当前分支

git pull origin main git pull

配置 Git

设置配置选项

git config user.name 'Your Name'

全局设置选项

git config --global ...

添加别名

git config alias.st status

查看所有可能的配置选项

man git-config