Git 的常用命令和工作流程有哪些?
基本操作
# 初始化与克隆
git init
git clone <url>
# 基本工作流
git status # 查看状态
git add . # 暂存所有
git add <file> # 暂存指定文件
git commit -m "message" # 提交
git push origin main # 推送
git pull origin main # 拉取
# 查看历史
git log --oneline --graph
git diff # 工作区 vs 暂存区
git diff --cached # 暂存区 vs 最新提交分支操作
git branch # 查看分支
git branch <name> # 创建分支
git checkout <name> # 切换分支
git checkout -b <name> # 创建并切换
git switch <name> # 切换(新命令)
git switch -c <name> # 创建并切换
git merge <branch> # 合并分支
git rebase <branch> # 变基
git branch -d <name> # 删除分支
git branch -D <name> # 强制删除撤销操作
git checkout -- <file> # 撤销工作区修改
git restore <file> # 同上(新命令)
git reset HEAD <file> # 撤销暂存
git restore --staged <file> # 同上(新命令)
git commit --amend # 修改最后一次提交
git reset --soft HEAD~1 # 撤销提交,保留改动
git reset --hard HEAD~1 # 撤销提交,丢弃改动(危险)
git revert <commit> # 创建反向提交(安全)合并 vs 变基
# merge:保留分支历史
git checkout main
git merge feature
# ──●──●──●───● (main)
# ╲ ╱
# ●──● (feature)
# rebase:线性历史
git checkout feature
git rebase main
git checkout main
git merge feature
# ──●──●──●──●──● (main,线性)rebase 金科玉律:不要 rebase 已推送到远程的公共分支!
储藏(Stash)
git stash # 储藏当前改动
git stash save "msg" # 带消息
git stash list # 查看储藏列表
git stash pop # 恢复并删除储藏
git stash apply # 恢复但不删除
git stash drop # 删除储藏远程操作
git remote add origin <url>
git remote -v
git push -u origin main # -u 设置上游
git push --force-with-lease # 安全的强制推送
git fetch origin # 获取但不合并
git pull --rebase origin main # 拉取并变基常见工作流
Git Flow:
main ← 生产分支
develop ← 开发分支
feature/* ← 功能分支
release/* ← 发布分支
hotfix/* ← 紧急修复GitHub Flow(简单):
main ← 直接在 feature 分支开发 → PR → 合并到 main常见问题处理
# 合并冲突
git merge feature
# 手动解决冲突文件
git add .
git commit
# 撤回已推送的提交
git revert <commit>
git push origin main
# 找回删除的分支
git reflog
git checkout <commit-hash>
git branch recovered <commit-hash>.gitignore
node_modules/
dist/
.env
*.log
.DS_Store
.vscode/