0%

Git 常用命令速查:从入门到精通

Git 常用命令速查:从入门到精通

本文整理了 Git 开发中最常用的命令和技巧,涵盖基础操作、分支管理、远程协作、问题排查等场景,是开发者的速查手册。

一、Git 基础配置

1.1 用户信息配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 全局配置(所有仓库)
git config --global user.name "John Doe"
git config --global user.email "john@example.com"

# 查看配置
git config --list
git config user.name
git config user.email

# 编辑配置文件
git config --global --edit

# 常用别名配置
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --oneline --graph --all"

1.2 SSH 密钥配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 生成 SSH 密钥
ssh-keygen -t ed25519 -C "your_email@example.com"

# 查看公钥
cat ~/.ssh/id_ed25519.pub

# 添加到 SSH agent
ssh-add ~/.ssh/id_ed25519

# 测试连接 GitHub
ssh -T git@github.com

# 测试连接 GitLab
ssh -T git@gitlab.com

1.3 常用 Git 配置优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 自动修正命令
git config --global help.autocorrect 1

# 默认使用 rebase
git config --global pull.rebase true

# 显示所有分支的图形化日志
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

# 忽略文件权限变化
git config --global core.filemode false

# 使用 VSCode 作为默认编辑器
git config --global core.editor "code --wait"

# 使用 Beyond Compare 作为 difftool
git config --global diff.tool bc3
git config --global difftool.bc3.trustexitcode true

# 使用 Beyond Compare 作为 mergetool
git config --global merge.tool bc3
git config --global mergetool.bc3.trustexitcode true

二、仓库操作

2.1 创建仓库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 初始化新仓库
git init
git init my-project

# 克隆远程仓库
git clone https://github.com/user/repo.git
git clone git@github.com:user/repo.git

# 克隆指定分支
git clone -b develop https://github.com/user/repo.git

# 克隆深度(只克隆最近 N 次提交)
git clone --depth 1 https://github.com/user/repo.git

# 克隆子模块
git clone --recursive https://github.com/user/repo.git

2.2 查看状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 查看仓库状态
git status
git status -s # 简短格式

# 查看提交历史
git log
git log --oneline
git log --graph --oneline --all
git log -n 5 # 最近 5 条

# 查看某文件的修改历史
git log --follow path/to/file

# 查看某人的提交
git log --author="John"

# 查看时间范围内的提交
git log --since="2 weeks ago"
git log --until="2024-01-01"

# 查看统计信息
git log --stat
git log --shortstat
git log --numstat

# 查看某次提交的详细内容
git show commit_id
git show --stat commit_id

2.3 差异比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 工作区 vs 暂存区
git diff

# 暂存区 vs 最新提交
git diff --cached
git diff --staged

# 工作区 vs 最新提交
git diff HEAD

# 两个提交之间的差异
git diff commit1 commit2
git diff commit1..commit2

# 两个分支之间的差异
git diff branch1 branch2

# 只比较某个文件
git diff path/to/file

# 忽略空白字符
git diff -w

# 生成补丁文件
git diff > patch.diff
git diff commit1 commit2 > patch.diff

三、文件操作

3.1 添加文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 添加指定文件
git add file.txt
git add dir/file.txt

# 添加所有文件
git add .
git add -A

# 添加所有修改的文件(不包括新文件)
git add -u

# 交互式添加
git add -p
git add -i

# 查看暂存区内容
git diff --cached

3.2 忽略文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 创建 .gitignore 文件
cat > .gitignore << EOF
# 编译产物
*.class
*.o
*.so
build/
dist/
target/

# 依赖目录
node_modules/
vendor/
__pycache__/

# 配置文件
.env
*.local
config.local.js

# IDE 文件
.idea/
.vscode/
*.swp
*.swo

# 系统文件
.DS_Store
Thumbs.db

# 日志文件
*.log
logs/

# 临时文件
tmp/
temp/
*.tmp
EOF

# 查看忽略规则
git check-ignore -v file.txt

# 测试忽略规则
git check-ignore *.log

3.3 删除文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 删除文件(工作区和暂存区)
git rm file.txt

# 删除目录
git rm -r dir/

# 只从暂存区删除(保留工作区文件)
git rm --cached file.txt

# 删除已修改但未暂存的文件
git checkout -- file.txt

# 恢复误删的文件
git checkout HEAD -- file.txt

3.4 移动/重命名文件

1
2
3
4
5
6
7
8
9
# 重命名文件
git mv old_name.txt new_name.txt

# 移动文件
git mv file.txt dir/file.txt

# 重命名后 Git 未识别
git add -A
git status # Git 会自动识别重命名

四、提交操作

4.1 基本提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 提交暂存区
git commit -m "feat: add user authentication"

# 提交并添加描述
git commit -m "feat: add user authentication" -m "Implemented JWT-based authentication"

# 提交所有修改的文件
git commit -am "fix: resolve login bug"

# 修改最后一次提交
git commit --amend
git commit --amend -m "new commit message"

# 提交时跳过预提交钩子
git commit --no-verify

4.2 提交规范

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Conventional Commits 格式
<type>(<scope>): <subject>

# type 类型
feat: 新功能
fix: 修复 bug
docs: 文档更新
style: 代码格式(不影响功能)
refactor: 重构
test: 测试相关
chore: 构建过程或辅助工具变动

# 示例
feat(auth): add login functionality
fix(api): resolve null pointer exception
docs(readme): update installation guide
style(format): format code with prettier
refactor(core): simplify user service
test(unit): add unit tests for auth module
chore(deps): upgrade dependencies

4.3 撤销提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 撤销工作区修改
git checkout -- file.txt
git restore file.txt # Git 2.23+

# 撤销暂存区修改
git reset HEAD file.txt
git restore --staged file.txt # Git 2.23+

# 撤销最后一次提交(保留修改)
git reset --soft HEAD~1
git reset --soft commit_id

# 撤销提交并丢弃修改
git reset --hard HEAD~1
git reset --hard commit_id

# 撤销远程已推送的提交(危险!)
git reset --hard HEAD~1
git push --force

# 安全撤销远程提交(推荐)
git revert commit_id
git push

4.4 查看提交历史

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 简洁的提交历史
git log --oneline

# 图形化提交历史
git log --graph --oneline --all

# 带统计信息的提交历史
git log --stat

# 搜索提交信息
git log --grep="bug fix"
git log --grep="feat" --oneline

# 查看某文件的提交历史
git log --follow -- path/to/file

# 查看某人的提交
git log --author="John" --oneline

# 查看时间范围内的提交
git log --since="2 weeks ago" --until="yesterday"

五、分支管理

5.1 分支基础操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 查看分支
git branch
git branch -a # 所有分支(包括远程)
git branch -v # 显示最后一次提交

# 创建分支
git branch feature/login
git branch feature/login commit_id

# 切换分支
git checkout feature/login
git switch feature/login # Git 2.23+

# 创建并切换分支
git checkout -b feature/login
git switch -c feature/login # Git 2.23+

# 删除分支
git branch -d feature/login # 安全删除(已合并)
git branch -D feature/login # 强制删除(未合并)

# 重命名分支
git branch -m old-name new-name
git branch -m new-name # 当前分支

5.2 分支合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 合并分支到当前分支
git checkout main
git merge feature/login

# 快进合并(不创建合并提交)
git merge --ff-only feature/login

# 禁止快进合并(强制创建合并提交)
git merge --no-ff feature/login

# 合并时压缩提交
git merge --squash feature/login

# 查看合并冲突
git diff --name-only --diff-filter=U
git diff # 查看冲突内容

# 解决冲突后标记为已解决
git add file.txt

# 取消合并
git merge --abort

5.3 分支变基(Rebase)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 变基操作
git checkout feature/login
git rebase main

# 交互式变基
git rebase -i HEAD~3
git rebase -i commit_id

# 变基交互命令
# pick: 使用提交
# reword: 使用提交,修改提交信息
# edit: 使用提交,暂停以便修改
# squash: 使用提交,压缩到上一个提交
# fixup: 使用提交,丢弃提交信息
# drop: 删除提交

# 继续变基
git rebase --continue

# 跳过当前提交
git rebase --skip

# 取消变基
git rebase --abort

# 变基到上游分支
git pull --rebase

5.4 分支管理最佳实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 查看已合并的分支
git branch --merged

# 查看未合并的分支
git branch --no-merged

# 查看分支的提交关系
git log --oneline --graph --all --decorate

# 清理已合并的本地分支
git branch --merged | grep -v "\*\|main\|develop" | xargs -n 1 git branch -d

# 查看远程跟踪分支
git branch -r

# 删除远程已删除的分支
git fetch -p
git remote prune origin

六、远程协作

6.1 远程仓库操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 查看远程仓库
git remote
git remote -v

# 添加远程仓库
git remote add origin https://github.com/user/repo.git
git remote add origin git@github.com:user/repo.git

# 修改远程仓库 URL
git remote set-url origin https://github.com/user/new-repo.git

# 删除远程仓库
git remote remove origin

# 重命名远程仓库
git remote rename origin upstream

# 获取远程仓库信息
git remote show origin

6.2 拉取和推送

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 拉取远程分支
git fetch origin
git fetch origin feature/login

# 拉取并合并
git pull origin main
git pull # 默认当前分支的 upstream

# 拉取并变基
git pull --rebase origin main

# 推送分支
git push origin feature/login
git push # 推送当前分支

# 推送并设置 upstream
git push -u origin feature/login

# 强制推送(危险!)
git push --force
git push --force-with-lease # 更安全

# 推送所有分支
git push --all origin

# 推送所有标签
git push --tags origin

# 删除远程分支
git push origin --delete feature/login
git push origin :feature/login # 旧语法

6.3 标签管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 查看标签
git tag
git tag -l "v1.*"

# 创建标签
git tag v1.0.0
git tag v1.0.0 commit_id

# 创建带注释的标签
git tag -a v1.0.0 -m "Release version 1.0.0"

# 查看标签信息
git show v1.0.0

# 推送标签
git push origin v1.0.0
git push --tags

# 删除本地标签
git tag -d v1.0.0

# 删除远程标签
git push origin --delete v1.0.0
git push origin :refs/tags/v1.0.0

# 检出标签
git checkout v1.0.0

6.4 Git Flow 工作流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 初始化 Git Flow
git flow init

# 开始新功能
git flow feature start login
git flow feature finish login

# 发布新版本
git flow release start 1.0.0
git flow release finish 1.0.0

# 修复生产 bug
git flow hotstart critical-bug
git flow hotfix finish critical-bug

七、高级技巧

7.1 暂存(Stash)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 暂存当前修改
git stash
git stash save "WIP: login feature"

# 查看暂存列表
git stash list

# 应用暂存(不删除)
git stash apply
git stash apply stash@{1}

# 应用并删除暂存
git stash pop
git stash pop stash@{1}

# 删除暂存
git stash drop
git stash drop stash@{1}

# 清空所有暂存
git stash clear

# 从暂存创建分支
git stash branch feature/login stash@{0}

# 暂存未跟踪的文件
git stash -u
git stash --include-untracked

# 暂存所有文件(包括已删除)
git stash -a
git stash --all

7.2 樱桃拣选(Cherry-pick)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 拣选单个提交
git cherry-pick commit_id

# 拣选多个提交
git cherry-pick commit1 commit2 commit3

# 拣选提交范围
git cherry-pick commit1..commit2

# 拣选时不提交
git cherry-pick --no-commit commit_id

# 拣选时编辑提交信息
git cherry-pick --edit commit_id

# 取消樱桃拣选
git cherry-pick --abort

# 继续樱桃拣选(解决冲突后)
git cherry-pick --continue

7.3 二分查找(Bisect)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 开始二分查找
git bisect start

# 标记当前为坏版本
git bisect bad

# 标记某版本为好版本
git bisect good v1.0.0

# Git 自动切换到中间版本,测试后继续标记
git bisect good # 或 git bisect bad

# 自动二分查找
git bisect run ./test-script.sh

# 结束二分查找
git bisect reset

# 查看二分查找日志
git bisect log

7.4 子模块(Submodule)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 添加子模块
git submodule add https://github.com/user/lib.git libs/lib

# 初始化子模块
git submodule init

# 更新子模块
git submodule update
git submodule update --init --recursive

# 查看子模块状态
git submodule status

# 更新子模块到最新版本
git submodule update --remote

# 删除子模块
git submodule deinit libs/lib
git rm libs/lib
rm -rf .git/modules/libs/lib

7.5 Git Hooks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Git Hooks 目录
ls .git/hooks/

# 常用 Hooks
pre-commit # 提交前检查
pre-push # 推送前检查
commit-msg # 提交信息检查
post-merge # 合并后执行

# 启用 Hook
cp .git/hooks/pre-commit.sample .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

# 示例:pre-commit 检查
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
# 检查是否有调试代码
if git diff --cached | grep -E "console\.log|debugger"; then
echo "Error: Found debug code"
exit 1
fi

# 运行代码检查
npm run lint
EOF

chmod +x .git/hooks/pre-commit

八、问题排查

8.1 查看修改历史

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 谁修改了某行代码
git blame file.txt
git blame -L 10,20 file.txt # 查看特定行

# 查看某次提交引入的修改
git show commit_id

# 查看某文件的修改历史
git log --follow -- path/to/file

# 查找引入 bug 的提交
git bisect start
git bisect bad
git bisect good v1.0.0

8.2 恢复丢失的提交

1
2
3
4
5
6
7
8
9
10
11
12
13
# 查看 reflog
git reflog
git reflog show --all

# 恢复丢失的提交
git reset --hard HEAD@{1}
git checkout -b recovery-branch commit_id

# 查看 dangling 提交
git fsck --lost-found

# 恢复 dangling 提交
git cherry-pick commit_id

8.3 解决常见问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 问题:提交信息写错
git commit --amend -m "correct message"

# 问题:漏提交了文件
git add forgotten_file.txt
git commit --amend --no-edit

# 问题:提交到了错误的分支
git reset --hard HEAD~1 # 撤销提交
git checkout correct-branch
git cherry-pick original-branch

# 问题:合并冲突
git mergetool # 使用图形化工具
git diff --name-only --diff-filter=U # 查看冲突文件

# 问题:误删了分支
git reflog
git branch recovered-branch commit_id

# 问题:Git 仓库损坏
git fsck
git gc

8.4 性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 清理不必要的文件
git gc
git gc --aggressive

# 清理远程跟踪分支
git remote prune origin

# 查看仓库大小
git count-objects -v
git du -sh .git/objects/*

# 查找大文件
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | awk '/^blob/ {print substr($0,6)}' | sort -k2 -nr | head -20

# 从历史中删除大文件
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch path/to/large-file' --prune-empty --tag-name-filter cat -- --all

九、实用脚本

9.1 日常开发脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 快速创建功能分支
function git-feat() {
git checkout -b "feat/$1"
}

# 快速创建修复分支
function git-fix() {
git checkout -b "fix/$1"
}

# 提交并推送
function git-commit-push() {
git add -A
git commit -m "$1"
git push -u origin $(git branch --show-current)
}

# 同步主分支
function git-sync-main() {
git fetch origin
git rebase origin/main
}

# 清理已合并分支
function git-cleanup() {
git branch --merged | grep -v "\*\|main\|develop" | xargs -n 1 git branch -d
}

# 查看今日提交
function git-today() {
git log --since="today" --author="$(git config user.name)"
}

9.2 Git 配置模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# .gitconfig 模板
[alias]
lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
st = status -s
co = checkout
br = branch
ci = commit
last = log -1 HEAD
unstage = reset HEAD --
who = blame -L -20,-0

[user]
name = Your Name
email = your.email@example.com

[core]
editor = code --wait
autocrlf = input
filemode = false

[pull]
rebase = true

[push]
default = simple

[merge]
tool = vscode

[difftool "vscode"]
cmd = code --wait --diff $LOCAL $REMOTE

十、总结

Git 是开发者必备的工具,掌握常用命令可以大幅提升开发效率。关键要点:

  1. 基础操作:add、commit、push、pull
  2. 分支管理:branch、checkout、merge、rebase
  3. 问题排查:log、diff、blame、reflog
  4. 高级技巧:stash、cherry-pick、bisect

建议将常用命令配置为别名,并建立适合自己的工作流。


参考资料: