Git 开发常用命令大全
目录
一、覆盖上一次提交
1. 使用 git commit –amend(最常用)
这会修改最近一次提交,可以将新的更改合并到上一次提交中。
1 2 3 4 5 6 7 8 9 10 11
| git add .
git commit --amend
git commit --amend --no-edit
git commit --amend --author="新作者 <email@example.com>"
|
2. 如果已经推送到远程仓库
1 2 3 4 5 6
| git add . git commit --amend
git push --force-with-lease origin 分支名
|
3. 使用 git reset 然后重新提交
1 2 3 4 5 6 7 8
| git reset --soft HEAD~1
git status
git commit -m "新的提交信息"
|
4. 具体使用场景示例
场景1:忘记添加文件到上次提交
1 2 3
| git add 忘记的文件.txt git commit --amend --no-edit
|
场景2:修改提交信息
1 2
| git commit --amend -m "新的提交信息"
|
场景3:修改提交的作者信息
1
| git commit --amend --author="新姓名 <new-email@example.com>"
|
5. 重要注意事项
- 只适用于本地最新提交:
--amend 只能修改最近一次提交
- 已推送的提交:如果已经推送到远程,需要强制推送
- 协作分支:在共享分支上谨慎使用,可能会影响其他协作者
- **推荐使用
--force-with-lease**:比 --force 更安全
6. 完整工作流程示例
1 2 3 4 5 6 7 8 9 10 11
| echo "新内容" >> file.txt
git add file.txt
git commit --amend
git push --force-with-lease origin main
|
推荐:在个人分支或功能分支上可以自由使用 --amend,但在主分支或共享分支上要谨慎使用。
返回目录
二、删除某次提交
1. 使用 git revert(推荐用于共享仓库)
这会创建一个新的提交来撤销指定提交的更改,不会修改历史记录。
1 2 3 4 5 6 7 8
| git revert <commit-hash>
git revert HEAD
git revert <commitA>..<commitB>
|
2. 使用 git reset(适用于本地仓库)
这会直接删除提交记录,会重写历史,不推荐用于已推送到远程仓库的提交。
1 2 3 4 5 6 7 8 9 10 11 12
| git reset --soft <commit-hash>
git reset <commit-hash> git reset --mixed <commit-hash>
git reset --hard <commit-hash>
git reset --hard HEAD~1
|
3. 使用 git rebase 交互式模式
适用于删除中间某次提交或重新排列提交历史。
1 2 3 4 5
| git rebase -i HEAD~n
git rebase -i <commit-hash>
|
在交互式界面中,将要删除的提交前的 pick 改为 drop 或直接删除该行。
4. 使用 git cherry-pick 选择性应用提交
如果你想保留某些提交但删除其他提交:
1 2 3 4 5
| git checkout -b new-branch <base-commit>
git cherry-pick <commit-hash1> <commit-hash2> ...
|
5. 注意事项
- git revert:最安全,适用于公共分支,不会影响其他协作者
- git reset 和 git rebase:会重写历史,只适用于本地分支或私有分支
- 如果已经推送到远程仓库,使用
git push --force-with-lease(比 --force 更安全)来强制推送
6. 示例场景
1 2 3 4 5 6 7 8 9 10
| git revert abc1234 git push origin main
git reset --hard HEAD~3
git rebase -i abc1234^
|
选择哪种方法取决于你的具体需求和是否已经将提交推送到远程仓库。
返回目录
三、实用技巧总结
安全操作建议
- **优先使用
git revert**:对于已推送的提交,使用 revert 最安全
- **使用
--force-with-lease**:比 --force 更安全,会检查远程分支是否有新的提交
- 在功能分支上操作:避免在主分支上直接修改历史
- 备份重要分支:在修改历史前先创建备份分支
常用命令速查
| 操作 |
命令 |
适用场景 |
| 修改最近提交 |
git commit --amend |
本地未推送的提交 |
| 安全撤销提交 |
git revert <hash> |
已推送的提交 |
| 删除本地提交 |
git reset --hard HEAD~n |
本地未推送的提交 |
| 交互式修改历史 |
git rebase -i HEAD~n |
本地分支历史整理 |
| 强制推送 |
git push --force-with-lease |
需要重写远程历史时 |
最佳实践
- 提交前检查:使用
git status 和 git diff 检查更改
- 小步提交:频繁提交,便于后续修改和回退
- 清晰的提交信息:使用规范的提交信息格式
- 分支策略:使用功能分支进行开发,避免直接在主分支上修改
返回目录