基础操作

初始化仓库

bash
1
git init

克隆远程仓库

bash
1
git clone https://github.com/user/repo.git

查看状态

bash
1
git status 	# 显示工作区和暂存区状态

添加到暂存区

bash
1
2
3
git add <file>	# 添加单个文件
git add .	# 添加所有修改和新文件 (不含删除)
git add -A	# 添加所有变更 (包括删除)

提交变更

bash
1
2
git commit -m "提交说明"		# 提交暂存区的修改
git commit -a -m "提交说明"	# 跳过 git add,直接提交所有已跟踪文件的修改

分支管理

查看分支

bash
1
2
git branch	# 本地分支
git branch -a	# 所有分支(含远程)

创建/切换分支

bash
1
2
3
git branch new-feature		# 创建分支
git checkout new-feature	# 切换分支
git checkout -b hotfix		# 创建并切换到新分支

合并分支

bash
1
2
git checkout main	# 切换到目标分支
git merge hotfix	# 合并 hotfix 到 main

删除分支

bash
1
2
git branch -d old-branch	# 删除已合并分支
git branch -D old-branch	# 强制删除未合并分支

远程操作

关联远程仓库

bash
1
git remote add origin https://github.com/user/repo.git

推送到远程

bash
1
2
git push -u origin main		# -u 设置默认上游分支
git push origin feature		# 推送到特定分支

拉取更新

bash
1
2
git pull origin main		# 拉取并合并 (= git fetch + git merge)
git fetch origin		# 仅获取远程更新,不自动合并

跟踪远程分支

bash
1
git checkout --track origin/dev		# 创建本地分支并跟踪远程分支

撤销操作

撤销工作区修改

bash
1
git checkout -- <file>	# 丢弃指定文件的修改

撤销暂存区修改

bash
1
git reset HEAD <file>	# 将文件移出暂存区 (保留修改)

重置提交

bash
1
2
3
git reset --soft HEAD^		# 撤销 commit,保留修改到暂存区
git reset --mixed HEAD^		# 撤销 commit 和 add (默认)
git reset --hard HEAD^		# 彻底丢弃最近一次 commit (⚠️慎用!)

回滚远程提交

bash
1
git revert <commit-id>	# 生成新提交来撤销指定提交 (推荐)

其他实用命令

查看提交历史

bash
1
2
3
git log			# 完整历史
git log --oneline	# 简洁模式
git log -p file.txt	# 查看文件的修改历史

贮藏修改

bash
1
2
git stash	# 临时保存修改
git stash pip	# 恢复最近一次贮藏

标签管理

bash
1
2
3
git tag v1.0			# 创建轻量标签
git tag -a 1.0 -m "发布说明"	# 创建附注标签
git push origin v1.0		# 推送标签到远程

注意事项

提交规范

  • 提交信息清晰明确(如:fix: 修复登录逻辑
  • 避免 git commit -m "更新" 等模糊描述

分支策略

  • main/master 分支保持稳定,仅用于发布
  • 新功能在 feature/* 分支开发,修复问题用 hotfix/*

强制推送风险

  • 避免 git push -f:会覆盖远程历史,可能导致他人代码丢失
  • 若必须强制推送,提前通知团队

.gitignore

务必配置(如忽略 node_modules/.env 等敏感文件)

plaintext
1
2
3
4
# .gitignore 示例
node_modules/
.env
*.log

冲突解决

合并时遇到冲突:

  1. 手动编辑标记冲突的文件 (<<<<<<<>>>>>>>)
  2. 解决后执行 git addgit commit

敏感数据处理

若误提交密码或密钥:

  • 使用 git filter-branchBFG Repo-Cleaner 彻底删除历史记录
  • 立即重置所有相关凭据

场景示例

紧急修复生产问题

bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
git checkout main
git pull origin main	# 确保同步
git checkout -b hotfix-login

// 修复代码 ...

git add .
git commit -m "fix: 解决登录崩溃问题"
git push origin hotfix-login

// 创建 Pull Request 合并到 main

撤销未推送的提交

bash
1
2
3
git reset --soft HEAD~1		# 保留修改到暂存区

# 修改后提交

恢复误删分支

bash
1
2
git reflog		# 查找分支最后的 commit ID
git checkout -b recovered-branch <commit-id>

提示:重要操作前用 git status 确认当前状态,避免误操作。善用 git diff 对比差异。