
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'
在分支间移动
切换分支
git switch <name> 或 git checkout <name>创建分支
git switch -c <name> 或 git checkout -b <name>列出分支
git branch
按最后提交时间排序列出分支
git branch --sort=-committerdate
删除分支
git branch -d <name>
强制删除分支
git branch -D <name>
比较暂存区/工作区差异 (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引用提交的方式
每当我们提到 <commit> 时,你可以使用以下任何一种
- 分支名
- main
- 标签 (Tag)
- v0.1
- 提交 ID (Hash)
- 3e887ab
- 远程分支
- origin/main
- 当前提交
- HEAD
- 3个提交之前
- HEAD^^^ 或 HEAD~3
丢弃更改
删除单个文件的未暂存更改
git restore <file> 或 git checkout <file>删除单个文件的所有已暂存和未暂存更改
git restore --staged --worktree <file> 或 git checkout HEAD <file>删除所有已暂存和未暂存的更改
git reset --hard
删除未跟踪的文件
git clean
“贮藏 (Stash)”所有已暂存和未暂存的更改
git stash
编辑历史
“撤销”最近的一次提交(保持工作目录不变)
git reset HEAD^
将最后 5 个提交压缩为一个
git rebase -i HEAD~6
然后将任何想要与前一个提交合并的提交从 "pick" 改为 "fixup"
撤销失败的变基 (Rebase)
git reflog BRANCHNAME
然后在 reflog 中手动找到正确的提交 ID,执行
git reset --hard <commit>
修改提交消息(或添加遗漏的文件)
git commit --amend
代码考古
查看分支历史
git log main git log --graph main git log --oneline显示修改过某个文件的所有提交
git log <file>
显示修改过某个文件的所有提交,包括重命名之前
git log --follow <file>
查找所有添加或删除过某些文本的提交
git log -G banana
显示文件中每一行最后是谁修改的
git blame <file>
合并分叉的分支
使用 Rebase 合并
git switch banana git rebase main
使用 Merge 合并
git switch main git merge banana
使用 Squash Merge 合并
git switch main git merge --squash banana git commit
使分支与另一个分支保持同步(即“快进合并”)
git switch main git merge banana
将一个提交复制到当前分支
git cherry-pick <commit>
恢复旧文件
获取另一个提交中的文件版本
git checkout <commit> <file> 或 git restore <file> --source <commit>添加远程仓库
git remote add <name> <url>
推送更改
将 main 分支推送到远程 origin
git push origin main
将当前分支推送到其对应的远程“跟踪分支”
git push
推送一个从未推送过的分支
git push -u origin <name>
强制推送
git push --force-with-lease
推送标签
git push --tags
拉取更改
获取更改(但不改变任何本地分支)
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
重要文件
本地 Git 配置
.git/config
全局 Git 配置
~/.gitconfig
忽略文件列表
.gitignore