跳到主要内容

Git 使用指南

基础配置

git config --global user.name "Your Name"
git config --global user.email "email@example.com"
git config --global init.defaultBranch main

常用命令速查

仓库操作

命令说明
git init初始化仓库
git clone <url>克隆远程仓库
git remote add origin <url>关联远程仓库

暂存与提交

命令说明
git add <file>暂存指定文件
git add .暂存所有变更
git commit -m "msg"提交
git commit --amend修改最近一次提交

分支管理

命令说明
git branch列出本地分支
git branch -a列出所有分支(含远程)
git branch <name>创建分支
git switch <name>切换分支
git switch -c <name>创建并切换
git merge <branch>合并分支到当前分支
git branch -d <name>删除本地分支

远程同步

命令说明
git fetch拉取远程更新(不合并)
git pull拉取并合并(= fetch + merge)
git push推送本地提交
git push -u origin <branch>首次推送并设置上游

查看历史

命令说明
git log --oneline简洁提交历史
git log --graph --all分支图
git diff查看未暂存的变更
git diff --staged查看已暂存的变更
git show <commit>查看某次提交详情

撤销操作

命令说明
git restore <file>撤销工作区修改
git restore --staged <file>取消暂存
git reset --soft HEAD~1撤销提交(保留修改)
git reset --hard HEAD~1撤销提交(丢弃修改)
git revert <commit>安全撤销(生成新提交)

暂存工作现场

命令说明
git stash暂存当前修改
git stash pop恢复最近一次暂存
git stash list查看暂存列表

典型工作流

单人开发

git switch -c feature/xxx
# ... 开发 ...
git add .
git commit -m "feat: xxx"
git switch main
git merge feature/xxx
git push

协作开发

git switch -c feature/xxx
# ... 开发 & 提交 ...
git push -u origin feature/xxx
# 在 GitHub/GitLab 创建 Pull Request
# 评审通过后合并

.gitignore 示例

# 编译产物
build/
dist/
*.o
*.exe

# 依赖
node_modules/
__pycache__/
*.pyc
.venv/

# IDE
.vscode/
.idea/
*.swp

# 环境变量
.env
.env.local

Git 提交规范

推荐 Conventional Commits:

  • feat: 新功能
  • fix: 修复 bug
  • docs: 文档
  • refactor: 重构
  • chore: 杂项
  • test: 测试

示例:git commit -m "feat: 添加用户登录功能"