目标:生产环境最常用 Git 命令速查(含 git worktree)。尽量短、尽量稳。


0. 日常最常用(先看这块就够)

git status
git pull --rebase
git switch -c feat/xxx
git add -A
git commit -m "xxx"
git push -u origin HEAD

1. 查看与定位

git status
git diff
git diff --staged
git log --oneline --decorate --graph -n 20
git show <commit>
git blame -L 120,180 path/to/file
  • 排障思路:先 status 看工作区/暂存区;再 diff 看改动;再 log/show 看提交。

2. 分支(生产最常见操作)

git branch
git branch -vv
git switch main
git switch -c hotfix/xxx
git fetch --all --prune
git push -u origin HEAD

3. 提交(尽量保持干净)

git add -A
git commit -m "xxx"

# 只提交部分文件(更安全)
git add path/to/file1 path/to/file2
git commit -m "xxx"

4. 同步(推荐 rebase 工作流)

git fetch origin

# 把本地分支“挪到”远端最新提交上(历史更直)
git rebase origin/main

# 或者一条命令:拉取并 rebase
git pull --rebase
  • 冲突处理:解决冲突 → git add -Agit rebase --continue;放弃本次 rebase 用 git rebase --abort

5. 回退/撤销(生产里务必谨慎)

# 放弃工作区改动(危险:丢改动)
git restore .

# 放弃某个文件改动
git restore path/to/file

# 取消暂存(不丢工作区改动)
git restore --staged .

# 撤销到某个提交(不改历史,适合“已推送”)
git revert <commit>
建议:已推送到远端/多人协作的分支,优先用 revert;不要轻易用重写历史(如强推)。

6. Tag(发布常用)

git tag
git tag -a v1.2.3 -m "release v1.2.3"
git push origin v1.2.3

7. git worktree(最常用)

场景:同一仓库同时开多个工作目录(例如一边修 hotfix、一边跑主分支)。

7.1 创建/列出/清理

# 列出现有 worktree
git worktree list

# 基于已有分支创建一个工作目录
git worktree add ../wt-hotfix hotfix/xxx

# 创建新分支并生成工作目录(常用)
git worktree add -b feat/yyy ../wt-feat

# 删除 worktree(先确保没有未提交改动)
git worktree remove ../wt-hotfix

# 清理已丢失的 worktree 记录(目录被手动删了时)
git worktree prune

7.2 常见注意点

  • 同一分支不能同时绑定两个 worktree:需要就新建分支(-b)。
  • 别在 worktree 里做破坏性清理:例如随手 git clean -fdx,除非你非常确定目录里没有需要的产物。
  • 冲突/构建更稳:worktree 能减少“切分支导致的依赖/构建缓存互相污染”。