如何删除本地和远程Git分支
分支是日常开发过程的一部分,并且是Git中最强大的功能之一。 分支合并后,除了历史研究之外,它没有任何作用。 在合并成功后,删除分支是常见的建议做法。
本指南介绍了如何删除本地和远程Git分支。
删除本地Git分支#
的 git branch
命令允许您列出,创建,重命名和删除分支。
要删除本地Git分支,请调用 git branch
用命令 -d
(--delete
)选项,后跟分支名称:
git branch -d branch_name
Deleted branch branch_name (was 17d9aa0).
如果您尝试删除具有未合并更改的分支,则会收到以下错误消息:
error: The branch 'branch_name' is not fully merged.
If you are sure you want to delete it, run 'git branch -D branch_name'.
从上面的消息中可以看到,要强制删除分支,请使用 -D
选项,这是快捷方式 --delete --force
:
git branch -D branch_name
请注意,如果删除未合并的分支,则将丢失该分支上的所有更改。
要列出所有包含未合并更改的分支,请使用 git branch --no-merged
命令。
如果您尝试删除当前分支,则会收到以下消息:
error: Cannot delete branch 'branch_name' checked out at '/path/to/repository'
您无法删除当前所在的分支。 首先,切换到另一个分支,然后删除 branch_name
:
git checkout master
git branch -d branch_name
删除远程Git分支#
在Git中,本地和远程分支是单独的对象。 删除本地分支不会删除远程分支。
要删除远程分支,请使用 git push
用命令 -d
(--delete
) 选项:
git push remote_name --delete branch_name
哪里 remote_name
通常是 origin
:
git push origin --delete branch_name
...
- [deleted] branch_name
还有另一种删除远程分支的命令,至少对我而言,这更难记住:
git push origin remote_name :branch_name
如果您正在与一群人一起进行项目,并且尝试删除已经被其他人删除的远程分支,则会收到以下错误消息:
error: unable to push to unqualified destination: branch_name The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref. error: failed to push some refs to '[email protected]:/my_repo'
在这种情况下,您需要将分支列表与:
git fetch -p
的 -p
选项告诉Git在获取之前删除远程存储库中不再存在的任何远程跟踪引用。
结论#
我们已经向您展示了如何删除本地和远程Git分支。 分支基本上是对更改快照的引用,并且生命周期很短。 一旦分支合并到主节点(或另一个主分支)中,就不再需要它,应该将其删除。
如果您遇到问题或有反馈,请在下面发表评论。
吉特