1. 安装与初始化
安装与全局配置
# 设置全局用户名与邮箱
git config --global user.name "your-name"
git config --global user.email "your-email@example.com"
# 查看配置
git config user.name
git config user.email
创建本地仓库
# 新建目录并进入
mkdir demo-repo && cd demo-repo
# 初始化 Git 仓库
git init
首次提交文件
# 新建文件
echo "Hello Git" > hello.txt
# 添加到暂存区
git add hello.txt
# 提交到本地仓库
git commit -m "Initial commit with hello.txt"
2. 版本控制核心操作
查看与对比
git status # 查看工作区状态
git diff # 工作区 vs 暂存区
git diff HEAD # 工作区 vs 最新提交
回退与恢复
# 查看提交历史
git log --oneline
# 回退到上一个版本
git reset --hard HEAD~1
# 后悔药:根据 reflog 找回
git reflog
git reset --hard abc1234
撤销修改
# 撤销工作区修改
git checkout -- file.txt
# 撤销已暂存的修改
git reset HEAD file.txt
删除文件
# 彻底删除
git rm file.txt
git commit -m "Remove file.txt"
# 误删恢复
git checkout HEAD -- file.txt
3. 连接远程仓库
关联并推送
# 添加远程地址
git remote add origin git@github.com:your-name/demo-repo.git
# 首次推送
git push -u origin main
# 后续推送
git push
SSH 密钥配置(解决 Permission denied)
# 生成密钥对
ssh-keygen -t rsa -C "your-email@example.com"
# 复制公钥内容
cat ~/.ssh/id_rsa.pub
# 在 GitHub → Settings → SSH keys → New SSH key 粘贴
克隆仓库
git clone git@github.com:your-name/demo-repo.git
4. 分支管理精要
创建与合并
# 创建并切换到新分支
git switch -c feature/login
# 合并分支
git switch main
git merge feature/login
冲突处理
# 当合并出现冲突时,手动编辑冲突文件
# 标记为已解决
git add conflicted-file.txt
git commit -m "Resolve merge conflict"
常用分支策略
- main:稳定发布分支
- dev:日常开发分支
- feature/xxx:功能开发分支
- hotfix/xxx:紧急修复分支
Rebase 整理历史
# 将 feature 分支的提交变基到 main 最新节点
git switch feature/login
git rebase main
多人协作流程
# 拉取最新代码
git pull --rebase origin main
# 推送本地分支
git push origin feature/login
# 创建 Pull Request 进行代码评审