目录
Git高级技巧与工作流
超越基础的 add、commit、push,掌握 Git 高级技巧让版本管理更加高效。
分支策略对比
| 策略 | 特点 | 适用场景 |
|---|---|---|
| Git Flow | 完整的分支模型 | 大型项目发版 |
| GitHub Flow | 简单的 PR 流程 | 持续部署 |
| Trunk-Based | 单主干开发 | 高频部署 |
rebase vs merge
bash
# merge:保留完整历史,产生合并提交
git checkout feature
git merge main
# rebase:将提交变基到目标分支,线性历史
git checkout feature
git rebase main
# 交互式 rebase:合并、修改、重排提交
git rebase -i HEAD~5交互式 rebase 操作
代码
pick a1b2c3d 添加登录功能
squash e4f5g6h 修复登录bug
reword i7j8k9l 更新文档
drop m0n1o2p 删除无用提交cherry-pick
将特定提交应用到当前分支:
bash
# 从其他分支摘取一个提交
git cherry-pick <commit-hash>
# 摘取多个提交
git cherry-pick commit1..commit3reflog 救命神器
bash
# 查看所有操作历史(包括已删除的分支)
git reflog
# 找回误删的分支
git checkout -b recovered-branch HEAD@{5}
# 找回 hard reset 之前的代码
git reset --hard HEAD@{3}git worktree
同时检出多个分支到不同目录:
bash
# 创建工作树
git worktree add ../project-hotfix hotfix-branch
# 列出所有工作树
git worktree list
# 删除工作树
git worktree remove ../project-hotfixstash 暂存
bash
# 暂存当前修改
git stash push -m "work in progress"
# 暂存包含未跟踪文件
git stash -u
# 查看暂存列表
git stash list
# 应用暂存(保留副本)
git stash apply stash@{0}
# 弹出暂存(删除副本)
git stash popGit Hooks
bash
# .git/hooks/pre-commit
#!/bin/sh
echo "Running linting..."
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed! Commit aborted."
exit 1
fi使用 Husky 管理 hooks:
json
{
"scripts": {
"prepare": "husky install"
},
"lint-staged": {
"*.{js,ts}": ["eslint --fix", "prettier --write"]
}
}bisect 二分查找 bug
bash
# 开始二分查找
git bisect start
# 标记当前版本有 bug
git bisect bad
# 标记已知正常的版本
git bisect good v1.0.0
# Git 自动切换到中间提交,测试后标记
git bisect good # 或 git bisect bad
# 找到引入 bug 的提交后结束
git bisect reset实用别名配置
bash
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 --decorate"
git config --global alias.last "log -1 HEAD"
git config --global alias.unstage "reset HEAD --"总结
Git 的高级技巧能极大提升开发效率。交互式 rebase 整理提交历史,reflog 找回误操作,worktree 实现多分支并行开发,bisect 快速定位 bug。结合合理的分支策略和 hooks 自动化,让团队协作更加顺畅。


评论 2