Git 是什么
Git 是目前最流行的分布式版本控制系统。它记录文件每次的改动,让你可以随时回退、分支开发、多人协作,是程序员的必备技能。
核心概念:工作区 → 暂存区(Stage)→ 仓库(Repository)。
# 配置身份(首次使用)
git config --global user.name "你的名字"
git config --global user.email "you@example.com"
# 查看配置
git config --list
基本操作
# 初始化仓库
git init
# 查看状态(最常用的命令之一)
git status
# 添加文件到暂存区
git add index.html # 添加单个
git add . # 添加全部
# 提交(-m 写提交说明)
git commit -m "feat: 添加首页"
# 查看提交历史
git log --oneline
# 查看某个文件的改动
git diff
✅ 提交规范
推荐 Conventional Commits 风格:feat: 新功能、fix: 修复、docs: 文档、refactor: 重构。分支管理
分支让多线开发互不干扰。每个新功能开一个分支,完成后合并回主分支:
# 查看分支
git branch
# 创建并切换到新分支
git checkout -b feature/login
# 切换分支
git checkout main
# 或(新写法)
git switch main
# 合并分支(先切回目标分支)
git merge feature/login
# 删除分支
git branch -d feature/login
⚠️ 注意
合并前先 git status 确认工作区干净,避免冲突时手忙脚乱。远程仓库协作
# 关联远程仓库
git remote add origin https://github.com/user/repo.git
# 推送(首次加 -u 记住关联)
git push -u origin main
# 拉取最新代码
git pull
# 克隆别人的项目
git clone https://github.com/user/repo.git
# 查看远程地址
git remote -v
日常开发循环:
git pull # 1. 同步最新代码
git checkout -b feat/xxx # 2. 新建功能分支
# ……写代码……
git add . # 3. 暂存
git commit -m "feat: xxx" # 4. 提交
git push # 5. 推送
# 6. 在 GitHub/Gitee 上发起 Pull Request
第 1 / 4 节