Git 常用命令速查
90% 的时间只用 10 个命令 — 把这页背下来。
起步
# 第一次用,告诉 git 你是谁(全局,只做一次)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
# 新建本地仓库
cd my-project
git init
# 克隆远端仓库
git clone https://github.com/user/repo.git
日常工作流(三板斧)
git add <file> # 暂存某个文件
git add . # 暂存所有改动
git commit -m "信息" # 提交暂存,带说明
git push # 推到远端
看状态和历史
git status # 当前改了什么
git log # 提交历史(详细)
git log --oneline # 提交历史(简洁)
git log --graph # 看分支图
git diff # 工作区 vs 暂存区
git diff --staged # 暂存区 vs 上次提交
撤销
git restore <file> # 丢弃工作区改动
git restore --staged <file> # 取消暂存
git commit --amend # 改最后一次提交(改说明/补文件)
git reset --hard HEAD^ # 撤销最后 1 次提交(危险)
分支
git branch # 看所有本地分支
git branch <name> # 新建分支
git checkout <name> # 切换到分支
git switch <name> # 切换(新命令)
git switch -c <name> # 新建并切换
git merge <name> # 把 name 合到当前分支
git branch -d <name> # 删分支(已合并)
远端
git remote -v # 看远端
git remote add origin <url> # 加远端
git push -u origin main # 首次推送
git pull # 拉取+合并
git fetch # 只拉取不合并
救命命令
| 状况 | 命令 |
|---|---|
| 提交信息写错了 | git commit --amend -m "新信息" |
| 想撤回某次提交(保留改动) | git reset --soft HEAD^ |
| 想撤回某次提交(丢弃改动,危险) | git reset --hard HEAD^ |
| commit 推到错分支 | git reset --soft HEAD^ 然后切到正确分支再 commit |
| 切换分支前有未提交改动 | git stash → 切换 → git stash pop |
| 想看某次提交改了什么 | git show <commit-hash> |
| 想找某行是谁改的 | git blame <file> |
易错点
git add .会暂存所有(包括不该传的) — 用git add -p一个个选- 提交前先 git status 看一下,确认改对了
- 绝不在 master/main 上直接改 — 建分支
- 看到
merge conflict别慌,看文件里<<<<<<<标记,手动改 git push --force会覆盖远端历史,团队项目慎用
推荐配置
# 设置默认分支名
git config --global init.defaultBranch main
# 漂亮的 log
git config --global alias.lg "log --graph --oneline --decorate"
# 自动换行
git config --global core.autocrlf input # Linux/Mac
git config --global core.autocrlf true # Windows