How do I delete a local branch in Git?

本文详细介绍了如何在Git中安全地删除本地和远程分支,包括正常情况下的`gitbranch-d`、强制删除`gitbranch-D`,以及恢复已删除分支的方法。还提到了使用Reflog工具和Tower客户端的便捷操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看到了一篇关于Git删除本地分支的文章,直接英文照搬过来,免得翻译过来曲解原文意思。

How do I delete a local branch in Git?

Git makes managing branches really easy - and deleting local branches is no exception:

$ git branch -d <local-branch>

In some cases, Git might refuse to delete your local branch: when it contains commits that haven’t been merged into any other local branches or pushed to a remote repository.
This is a very sensible rule that protects you from inadvertently losing commit data.

If you want to delete such a branch nonetheless (e.g. because you’ve programmed yourself into a dead end and produced commits that aren’t worth keeping) you can do so with the “-D” flag:

$ git branch -D <local-branch>

This will force deletion of the branch, even if it contains unmerged / unpushed commits. It goes without saying: please be careful with this command!

Can I undo deleting a branch?

In most cases, if you don’t let too much time pass, you can restore a deleted branch.

If you’re working with Git on the Command Line, you should take a look at a Git tool called “Reflog”.
Learn more about this in our free First Aid Kit for Git video series.

If you’re using the Tower Git client, you can simply press CMD+Z (or CTRL+Z on Windows) - like you would to undo changes in a text editor - to undo the deletion and restore the branch:

You can undo many other Git operations with this familiar keyboard shortcut.
Have a look at everything that Tower allows you to undo!

How do I delete a remote branch in Git?

To delete a remote branch, you need to use the “git push” command:

$ git push origin --delete <remote-branch-name>

Learn More

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值