Git 从入门到精通:常用命令与工作流

Git 从入门到精通:常用命令与工作流

Git 是每个开发者必须掌握的基础工具。但很多人只会 addcommitpush 三板斧,遇到冲突就慌。

今天从实用角度出发,带你掌握 Git 的核心命令和最佳工作流。


基础配置

装好 Git 后第一件事就是配置身份:

bash
git config --global user.name "Your Name"
git config --global user.email "your@email.com"

# 推荐配置
git config --global init.defaultBranch main
git config --global core.autocrlf input
git config --global pull.rebase true
git config --global fetch.prune true

日常开发流程

标准工作流

bash
# 拉取最新代码
git pull

# 创建功能分支
git checkout -b feature/my-new-feature

# ... 写代码 ...

# 查看变更
git status
git diff

# 暂存并提交
git add .
git commit -m "feat: 添加新功能"

# 推送分支
git push -u origin feature/my-new-feature

撤销操作

bash
# 撤销工作区修改
git checkout -- file.txt

# 撤销暂存
git reset HEAD file.txt

# 修改最后一次 commit
git commit --amend -m "新的提交信息"

# 回退到某个版本(保留修改)
git reset --soft HEAD~1

# 回退到某个版本(丢弃修改)
git reset --hard HEAD~1

分支管理策略

text
main          ●──────●──────────────●
               \    /              /
develop         ●──●──●────●────●
                      \    /    /
feature/a              ●──●──●

Git Flow 简化版

bash
# main 分支:生产环境代码,只接受合并
# develop 分支:开发主分支
# feature/*:功能分支
# hotfix/*:紧急修复

# 创建功能分支
git checkout -b feature/add-login develop

# 完成功能后合并回 develop
git checkout develop
git merge --no-ff feature/add-login

解决冲突

冲突发生时,Git 会在文件中标记:

text
<<<<<<< HEAD
你本地的修改
=======
远程的修改
>>>>>>> branch-name

手动编辑后:

bash
git add resolved-file.txt
git commit

交互式变基

合并多个 commit 保持历史整洁:

bash
# 合并最近 3 个 commit
git rebase -i HEAD~3

# 在编辑器中将 pick 改为 squash 或 fixup
pick abc123 第一次提交
squash def456 第二次提交
squash 789ghi 第三次提交

常用技巧

bash
# 查看简短的提交历史
git log --oneline --graph --all

# 查找是谁改了某行代码
git blame file.txt

# 暂存当前工作
git stash
git stash pop

# 查看某个文件的修改历史
git log -p file.txt

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

提交信息规范

使用 Conventional Commits 规范:

text
feat: 新功能
fix: 修复 bug
docs: 文档更新
style: 代码格式调整
refactor: 重构
test: 测试相关
chore: 构建/工具相关

.gitignore 模板

gitignore
# Node
node_modules/
npm-debug.log*
.env

# Python
__pycache__/
*.pyc
venv/

# 编辑器
.vscode/
.idea/
*.swp

# 构建产物
dist/
build/
*.log


Git 不难,关键是养成好习惯:小粒度提交、写清晰的 commit message、用分支隔离功能、经常 rebase 保持历史整洁。

推荐指数:⭐⭐⭐⭐⭐

官方文档:https://git-scm.com/doc

💬 评论区 (0)

暂无评论,快来抢沙发吧!