Git 速查表
常用 Git 命令分类速查(提交、分支、远程、撤销、变基等)。
本地处理
初始化 & 克隆
git init在当前目录初始化空仓库git clone <url>克隆远程仓库git clone --depth 1 <url>浅克隆(只取最近一次提交)git clone -b <branch> <url>克隆指定分支查看状态 & 历史
git status查看工作区状态git status -s简短输出(推荐日常使用)git log查看提交历史git log --oneline --graph --all图形化所有分支历史(最常用)git log -p <file>查看某文件的详细修改历史git log --since="2 weeks ago"查看最近 2 周的提交git show <commit>查看某次提交的详情git blame <file>查看文件每行最后修改人git reflog查看本地引用日志(救命用)暂存 & 提交
git add <file>暂存指定文件git add .暂存当前目录所有改动git add -p交互式暂存(按 hunk 选)git commit -m "msg"提交git commit --amend修改上一次提交(commit hash 会变)git commit --amend --no-edit修改上一次提交但保留原 messagegit restore --staged <file>取消暂存(保留改动)git restore <file>丢弃工作区修改(不可恢复)分支
git branch列出本地分支git branch -a列出所有分支(含远程)git branch <name>创建分支git switch <branch>切换分支(推荐,替代 checkout)git switch -c <branch>创建并切换分支git branch -d <branch>删除分支(已合并才允许)git branch -D <branch>强制删除分支git branch -m <new>重命名当前分支git merge <branch>合并分支到当前分支git merge --squash <branch>把分支所有改动压成单次提交远程仓库
git remote -v查看远程仓库地址git remote add origin <url>添加远程仓库git remote set-url origin <url>修改远程仓库地址git fetch拉取远程更新(不合并)git pull拉取并合并git pull --rebase拉取并变基(避免不必要的 merge commit)git push推送当前分支git push -u origin <branch>首次推送并设置上游git push --tags推送所有标签git push origin --delete <branch>删除远程分支变基 & 樱桃挑选
git rebase <branch>把当前分支变基到目标分支顶端git rebase -i HEAD~3交互式整理最近 3 次提交git rebase --continue解决冲突后继续 rebasegit rebase --abort取消 rebase 回到原状态git cherry-pick <commit>把某次提交摘到当前分支git cherry-pick <a>..<b>摘一段提交范围撤销 & 救命
git reset --soft HEAD~1撤销上次 commit,保留暂存与改动git reset --mixed HEAD~1撤销上次 commit,保留改动(默认)git reset --hard HEAD~1⚠️ 撤销上次 commit 并丢弃改动git revert <commit>产生一个反向提交以撤销(不改历史)git clean -fd⚠️ 删除未跟踪文件与目录git stash把当前改动临时收起git stash pop恢复最近一次 stashgit stash list列出所有 stashgit stash drop删除最近一次 stash标签
git tag列出所有标签git tag <name>在当前 commit 打轻量标签git tag -a v1.0.0 -m "release"打附注标签(推荐)git tag -d <name>删除本地标签git push origin <tag>推送指定标签git push origin --delete <tag>删除远程标签配置 & 别名
git config --global user.name "Your Name"设置用户名git config --global user.email "you@example.com"设置邮箱git config --global init.defaultBranch main设置新仓库默认分支为 maingit config --global core.editor "code --wait"设置默认编辑器为 VS Codegit config --global alias.st status别名:git st = git statusgit config --global alias.lg "log --oneline --graph --all"别名:git lg = 图形化历史