Git必备:20个高频命令与实战场景

11次阅读
没有评论

为什么需要这篇速查表

Git 的文档很全,但太全了。实际工作中,80% 的场景只用得到 20% 的命令。这篇把最常用的 20 个命令按场景整理,方便速查。

场景 1:日常提交

# 查看状态
git status

# 添加所有变更(慎用,建议先 status 确认)git add .

# 添加指定文件
git add src/index.js

# 提交(规范格式:type(scope): description)git commit -m "feat(auth): add login form validation"

# 推送到远程
git push origin main

场景 2:分支管理

# 创建并切换到新分支
git checkout -b feature/user-profile

# 查看所有分支(本地 + 远程)git branch -a

# 删除本地分支
git branch -d feature/old-feature

# 强制删除未合并的分支
git branch -D feature/abandoned

# 合并分支
git merge feature/user-profile

场景 3:撤销操作

# 撤销工作区的修改(危险!不可恢复)git checkout -- filename.js

# 撤销已 add 但未 commit 的修改
git reset HEAD filename.js

# 撤销最后一次 commit(保留修改)git reset --soft HEAD~1

# 撤销最后一次 commit(不保留修改,危险!)git reset --hard HEAD~1

# 用新 commit 覆盖错误的 commit
git commit --amend

警告:git reset –hard 会丢失所有未提交的修改,使用前务必确认。

场景 4:查看历史

# 查看提交历史(简洁版)git log --oneline

# 查看某文件的修改历史
git log -p filename.js

# 查看某次 commit 的详情
git show commit-hash

# 查看某行代码是谁写的(追责利器)git blame filename.js

场景 5:远程协作

# 拉取远程更新(不自动合并)git fetch origin

# 拉取并合并(等于 fetch+merge)git pull origin main

# 查看远程仓库信息
git remote -v

# 修改远程仓库地址
git remote set-url origin https:// 新地址.git

场景 6:暂存工作区

# 临时保存当前修改(还没 ready to commit)git stash

# 查看所有 stash
git stash list

# 恢复最近一次 stash
git stash pop

# 恢复指定的 stash
git stash apply stash@{2}

场景 7:标签管理

# 创建标签
git tag v1.2.0

# 创建带说明的标签
git tag -a v1.2.0 -m "发布 1.2.0 版本"

# 推送标签到远程
git push origin --tags

# 删除本地标签
git tag -d v1.2.0

场景 8:解决冲突

# 查看冲突文件
git status

# 手动解决冲突后,标记为解决
git add conflicted-file.js

# 取消合并(如果冲突太难解决)git merge --abort

# 查看合并后的差异
git diff --staged

Commit 规范(Conventional Commits)

类型 说明 示例
feat 新功能 feat(auth): add password reset
fix 修复 bug fix(api): handle timeout error
docs 文档变更 docs: update API documentation
style 代码格式(不影响功能) style: format code with prettier
refactor 重构 refactor(auth): simplify token logic
test 测试相关 test: add unit tests for user API
chore 构建 / 工具链变更 chore: upgrade webpack to v5

总结

Git 并不难,难的是在 正确的场景下用正确的命令。建议把这篇文章存下来,遇到不确定的操作时先查再动,避免不必要的代码丢失。

正文完
 0
评论(没有评论)