692 字
3 分钟
Git常用指令
Git 操作手册(实用全版)
一、基础概念
- 工作区:你改代码的地方
- 暂存区(index):准备提交的内容
- 仓库(repo):Git 管理的数据
- HEAD:当前指向的提交
- 分支:一条提交链
二、初始化与配置
git init # 初始化仓库git clone <url> # 克隆远程仓库
git config --global user.name "你的名字"git config --global user.email "你的邮箱"查看配置:
git config --list三、基本流程(最常用)
git status # 查看状态git add <file> # 添加到暂存区git add . # 全部添加
git commit -m "说明" # 提交
git log # 查看提交记录git log --oneline # 简洁版四、分支操作
git branch # 查看分支git branch <name> # 创建分支git checkout <name> # 切换分支git checkout -b <name> # 创建并切换
git switch <name> # 新写法(推荐)
git merge <name> # 合并分支删除分支:
git branch -d <name>五、远程仓库
git remote -v # 查看远程git remote add origin <url>
git push -u origin main # 推送git push # 后续直接推
git pull # 拉取并合并git fetch # 只拉取不合并六、撤销操作(重点)
1. 撤销工作区修改
git checkout -- <file># 或git restore <file>2. 撤销暂存区
git reset HEAD <file>3. 回退提交
git reset --soft HEAD~1 # 保留代码git reset --hard HEAD~1 # 全部回退(危险)4. 反向提交(安全)
git revert <commit>七、查看差异
git diff # 工作区 vs 暂存区git diff --cached # 暂存区 vs 仓库git diff HEAD # 工作区 vs 最新提交八、暂存(stash)
git stash # 临时保存git stash pop # 恢复并删除git stash list # 查看git stash apply # 恢复但不删九、标签(Tag)
git tag # 查看git tag v1.0 # 创建标签git push origin v1.0 # 推送标签十、日志与历史
git log --graph --oneline --allgit show <commit>git reflog # 查看操作历史(救命用)十一、冲突处理
出现冲突后:
<<<<<<< HEAD当前分支内容=======目标分支内容>>>>>>> branch处理步骤:
- 手动修改文件
- 删除冲突标记
git addgit commit
十二、rebase(进阶)
git rebase <branch>作用:
- 让提交更线性
- 替代 merge
交互式:
git rebase -i HEAD~3可:
- 合并提交
- 修改 commit message
- 删除提交
十三、常见工作流
1. 标准开发流程
git checkout -b feature/xxx# 开发git add .git commit -m "feat: xxx"
git pull --rebase origin maingit push origin feature/xxx2. 更新本地代码
git pull --rebase十四、忽略文件
.gitignore
node_modules/dist/*.log.env十五、子模块(了解)
git submodule add <url>git submodule update --init --recursive十六、常见坑
- ❌
git reset --hard会丢数据 - ❌ rebase 后不要强推公共分支
- ❌ 不要在 main 直接开发
- ❌ 忘记 pull 就 push → 冲突
十七、救命命令
git reflog # 找回误删提交git reset --hard <hash> # 回到某次状态