为什么要学 Git?
Git 是现代软件开发中最基础也是最核心的工具之一。无论你是做个人项目还是团队协作,版本控制都是不可或缺的技能。
基础概念
在开始之前,先了解几个核心概念:
工作区(Working Directory) → 暂存区(Staging Area) → 本地仓库(Local Repo) → 远程仓库(Remote Repo)
每次文件的修改都沿着这条路径流动,最终同步到远程仓库。
日常操作速查
1. 配置
# 设置用户名和邮箱(第一次使用 Git 时)
git config --global user.name "Nehemiab"
git config --global user.email "your-email@example.com"
# 查看配置
git config --list
2. 基本工作流
# 克隆仓库
git clone https://github.com/username/repo.git
# 查看状态
git status
# 添加文件到暂存区
git add filename # 添加单个文件
git add . # 添加所有变更
# 提交到本地仓库
git commit -m "feat: 添加了新功能"
# 推送到远程仓库
git push origin main
3. 分支管理
# 创建并切换分支
git checkout -b feature/new-feature
# 查看分支
git branch -a # 查看所有分支
# 合并分支
git checkout main
git merge feature/new-feature
# 删除分支
git branch -d feature/new-feature
Commit Message 规范
一个好的 commit message 应该清晰描述"为什么改"而非"改了什么"。推荐使用 Conventional Commits 规范:
<type>(<scope>): <description>
[optional body]
常用 type 类型:
| Type | 说明 |
|---|---|
| feat | 新功能 |
| fix | 修复 bug |
| docs | 文档更新 |
| refactor | 代码重构 |
| test | 测试相关 |
| chore | 构建/工具相关 |
.gitignore 配置
# 编译产物
*.o
*.class
build/
dist/
# 依赖目录
node_modules/
vendor/
# 环境配置
.env
.env.local
# IDE 配置
.vscode/
.idea/
# 操作系统文件
.DS_Store
Thumbs.db
我的 Git 配置推荐
这是我目前在用的 .gitconfig 配置:
[alias]
st = status
co = checkout
br = branch
ci = commit
lg = log --oneline --graph --all --decorate
undo = reset --soft HEAD~1
[core]
editor = nvim
autocrlf = input
[push]
default = current
总结
Git 的学习曲线确实存在,但只要掌握了上述核心操作,日常开发就完全够用了。更多的技巧可以在实际使用中慢慢积累。
推荐资源:
- Pro Git 中文版
- Learn Git Branching — 交互式学习 Git
记住:熟能生巧,多用自然就记住了。
评论