Git 常用命令速查表:从入门到实战
Git 是每位开发者的必备工具。本文整理了最实用的 Git 命令,从基础操作到高级技巧,帮你快速查阅、提升版本控制效率。
为什么需要 Git 速查表
Git 命令繁多,参数复杂,即使是有经验的开发者也经常需要查阅文档。一份实用的速查表能让你在忘记命令时快速找回记忆,大幅提升工作效率。
基础操作
初始化与克隆
# 初始化新仓库
git init
# 克隆远程仓库
git clone https://github.com/user/repo.git
# 克隆指定分支
git clone -b branch-name https://github.com/user/repo.git
查看状态
# 查看工作区状态
git status
# 查看简洁状态
git status -s
# 查看提交历史
git log --oneline --graph --all
分支管理
创建与切换
# 创建新分支
git branch feature-name
# 切换分支
git checkout feature-name
# 创建并切换(推荐)
git checkout -b feature-name
# 新版 Git 推荐使用 switch
git switch feature-name
git switch -c feature-name
合并与变基
# 合并分支到当前分支
git merge feature-name
# 变基(保持提交历史线性)
git rebase main
# 交互式变基(修改历史提交)
git rebase -i HEAD~3
暂存与提交
# 添加文件到暂存区
git add filename
git add . # 添加所有改动
# 提交
git commit -m "feat: add new feature"
# 修改上一次提交
git commit --amend
# 暂存当前改动(临时切换分支时用)
git stash
git stash pop # 恢复暂存
远程仓库
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
# 推送本地分支
git push origin main
# 拉取远程更新
git pull origin main
# 强制推送(慎用)
git push --force origin main
撤销操作
# 撤销工作区改动
git checkout -- filename
# 撤销暂存区改动
git reset HEAD filename
# 回退到指定提交
git reset --hard commit-hash
# 创建反向提交(安全撤销)
git revert commit-hash
高级技巧
查找 Bug 引入点
# 二分查找引入 bug 的提交
git bisect start
git bisect bad # 标记当前为 bad
git bisect good v1.0 # 标记某个历史版本为 good
# Git 会自动切换提交,按提示标记 good/bad
# 找到问题提交后:git bisect reset
清理分支
# 删除本地分支
git branch -d feature-name
# 删除远程分支
git push origin --delete feature-name
# 清理远程已删除的分支引用
git fetch --prune
常用别名配置
在 ~/.gitconfig 中添加别名,提升效率:
[alias]
co = checkout
br = branch
ci = commit
st = status
lg = log --oneline --graph --all
总结
掌握这些命令,日常开发中的版本控制需求基本都能覆盖。建议把这篇文章加入书签,随时查阅!
> **Pro Tip**: 使用 git help 可以随时查看任意命令的官方文档。