如何在本地和远程删除Git分支?

20371

尝试删除远程分支失败:

$ git branch -d remotes/origin/bugfix
error: branch 'remotes/origin/bugfix' not found.

$ git branch -d origin/bugfix
error: branch 'origin/bugfix' not found.

$ git branch -rd origin/bugfix
Deleted remote branch origin/bugfix (was 2a14ef7).

$ git push
Everything up-to-date

$ git pull
From github.com:gituser/gitproject

* [new branch] bugfix -> origin/bugfix
Already up-to-date.

我应该如何正确删除本地和远程的remotes/origin/bugfix分支?


1554
不好意思,这个问题已经有40个答案了。请问您还需要我翻译吗? - Robert Harvey
80
注意:针对 Git 2.5+(2015 年第二季度发布),准确的消息将会是“**deleted remote-tracking branch**”:请参见 https://github.com/git/git/commit/ccd593cffaa020ff767860ec211462b8dbd727a6#diff-d18f86ea14e2f1e5bff391b2e54438cbR268 - VonC
29
跳过前几个答案并直接跳到最佳答案:https://dev59.com/h3I-5IYBdhLWcg3wI0p9#23961231 。 要删除git分支,实际上有3个不同的分支需要删除! 这个答案明确了这个事实。 - Gabriel Staples
6
没有上下文,你的评论很令人困惑。这些“最佳”答案是否存在某种错误? - Nathan majicvr.com
17
@Nathan,不,他们没有错,但是“你不知道你不知道什么”是他们没有教授的内容,而我提供的链接使得这个重要的“未知未知”成为了“已知未知”,然后变成了“已知已知”。在阅读那篇回答之前,我不知道有一个本地分支、本地存储的远程跟踪分支和远程分支(1)(2)(3)。在那之前,我认为只有本地分支和远程分支。本地存储的远程跟踪分支是一个“未知未知”。让它从“未知未知”变成“已知已知”,这就是这篇回答最好的原因。 - Gabriel Staples
显示剩余5条评论
43个回答

58

执行之前

git branch --delete <branch>

确保先执行以下操作确定远程分支的确切名称:

git ls-remote

这将告诉您需要输入什么确切的<branch>值。(branch是大小写敏感的!)


48

这里是所有其他答案的混搭。它需要Ruby 1.9.3+,并且仅在OS X上进行测试。

将此文件命名为git-remove,使其可执行,并将其放在您的路径中。然后使用例如git remove temp

#!/usr/bin/env ruby
require 'io/console'

if __FILE__ == $0
      branch_name = ARGV[0] if (ARGV[0])
      print "Press Y to force delete local and remote branch #{branch_name}..."
    response = STDIN.getch
    if ['Y', 'y', 'yes'].include?(response)
      puts "\nContinuing."
      `git branch -D #{branch_name}`
      `git branch -D -r origin/#{branch_name}`
      `git push origin --delete #{branch_name}`
    else
      puts "\nQuitting."
    end
end

@chhh,那么您需要扩展此功能,将其变为一个变量而不是假设。 - Dan Rosenstark
3
抱歉,但为了这种工作安装Ruby还不如使用Bash实现更合理,因为它可以开箱即用。 - Reishin
1
@Reishin Ruby就像Bash一样安装在盒子上,至少在OSX上是这样的。请参见:https://dev59.com/43E95IYBdhLWcg3wXcrd,在这个主题中,SO已经将其作为基于观点的内容进行了丢弃。 - Dan Rosenstark
5
@Yar,这个链接超出了上下文的范围,涵盖的范围更广。我只说关于git的事情,而且这个话题并不是只针对OSX,所以在其他系统(例如* UNIX,Windows)选择它是奇怪的。 - Reishin

42
我将以下别名添加到我的.gitconfig文件中。这使我能够删除分支,无论是否指定分支名称。如果没有传入参数,则默认为当前分支的分支名称。
[alias]
    branch-name = rev-parse --abbrev-ref HEAD     

    rm-remote-branch = !"f() { branch=${1-$(git branch-name)}; git push origin :$branch; }; f"
    rm-local-branch = !"f() { branch=${1-$(git branch-name)}; git checkout master; git branch -d $branch; }; f"
    rm-branch-fully = !"f() { branch=${1-$(git branch-name)}; git rm-local-branch $branch; git rm-remote-branch $branch; }; f"

6
注意使用 -D 选项时要小心,在批处理中考虑使用较小的 -d 选项。 - Alwin Kesler
在我的情况下,我几乎总是在合并后删除(或者根本不需要合并)。使用较小的-d将要求在删除之前合并该分支,而使用-D则强制删除该分支。 - Jared Knipp

36

除了使用命令行删除远程分支外,另一种选择是使用GitHub分支页面

例如: https://github.com/angular/angular.js/branches

可以在GitHub存储库的代码 -> 分支页面找到。

尽管我通常更喜欢使用命令行,但这个GitHub页面向您展示了更多关于分支的信息,例如最近更新的日期和用户以及领先和落后的提交次数,当处理大量分支时非常有用。


35

虽然有好的解决方法,但是如果你有很多分支,手动一个一个地在本地和远程删除它们会是一项繁琐的任务。你可以使用这个脚本来自动化这些任务。

branch_not_delete=( "master" "develop" "our-branch-1" "our-branch-2")

for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master`; do

    # Delete prefix remotes/origin/ from branch name
    branch_name="$(awk '{gsub("remotes/origin/", "");print}' <<< $branch)"

    if ! [[ " ${branch_not_delete[*]} " == *" $branch_name "* ]]; then
        # Delete branch remotly and locally
        git push origin :$branch_name
    fi
done
  • 列出您不想删除的分支
  • 遍历远程分支,如果它们不在我们的“保留列表”中,则将其删除。

来源:一次性删除Git分支


1
当您链接到您所编写的外部资源时,您必须披露关联关系。 - Jean-François Fabre

31

使用Git Bash,您可以执行以下操作:

git branch --delete <branch>

或者

-

从GitHub桌面应用程序中,当你已经检出分支时,可以通过“Branch”菜单中的“Delete Branch”选项删除本地分支:

Enter image description here

如果你没有使用GitHub桌面应用程序,并且在本地源代码控制方面使用类似Visual Studio的IDE,则只需执行几个快速步骤:

  1. 检出希望删除的分支以外的其他分支。
  2. 右键单击要删除的分支。
  3. 从上下文菜单中选择Delete选项。

然后,一旦登录到您的GitHub在线账户,进入仓库并点击All Branches选项卡。从那里,只需点击您要删除的分支名称右侧的小垃圾桶图标即可。

Enter image description here

*请记住 - 如果该分支未发布,则无需尝试从您的在线仓库中删除它。


我在GitHub网站上看不到概述你的活跃状态所有分支选项卡。看起来这是一个旧的快照。在代码选项卡下,我看到了提交、分支、发布和贡献者等子选项卡。当我是存储库的所有者时,我会看到一个名为MIT的额外选项卡。 - RBT
git branch --delete <branch>不能删除远程分支,你需要使用git push <server> --delete <branch>来完成。 - Sheldon

21

我在我的.bash_aliases文件中创建了以下方便的函数:

git-delete-branch() 
{ 
    if [[ -n $1 ]]; then
        git checkout master > /dev/null;
        branch_name="$1";
        echo "Deleting local $branch_name branch...";
        git branch -D "$branch_name";
        echo "Deleting remote $branch_name branch...";
        git push origin --delete "$branch_name";
        git remote prune origin;
        echo "Your current branches are:";
        git branch -a;
    else
        echo "Usage: git-delete-branch <branch_name>";
    fi
}

13

最灵活的方法是使用自定义 Git 命令。例如,在您的$PATH中的某个位置创建以下 Python 脚本,命名为git-rmbranch并使其可执行:

#!/usr/bin/env python3

import argparse
import subprocess
import sys

def rmbranch(branch_name, remote, force):
    try:
        print(subprocess.run(['git', 'branch', '-D' if force else '-d', branch_name],
                             capture_output=True, check=True, encoding='utf-8').stdout, end='')
    except subprocess.CalledProcessError as exc:
        print(exc.stderr.replace(f'git branch -D {branch_name}', f'git rmbranch -f {branch_name}'), end='')
        return exc.returncode

    return subprocess.run(['git', 'push', remote, '--delete', branch_name]).returncode    

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Delete a Git branch locally and remotely.')
    parser.add_argument('-r', '--remote', default='origin', help="The remote name (defaults to 'origin')")
    parser.add_argument('-f', '--force', action='store_true', help='Force deletion of not fully merged branches')
    parser.add_argument('branch_name', help='The branch name')
    args = parser.parse_args()

    sys.exit(rmbranch(args.branch_name, args.remote, args.force))

然后,git rmbranch -h 将向您显示使用信息:

usage: git-rmbranch [-h] [-r REMOTE] [-f] branch_name

Delete a Git branch locally and remotely.

positional arguments:
  branch_name           The branch name

optional arguments:
  -h, --help            show this help message and exit
  -r REMOTE, --remote REMOTE
                        The remote name (defaults to 'origin')
  -f, --force           Force deletion of not fully merged branches
请注意, git push origin --delete <branch_name> 命令也会删除本地的远程跟踪分支(默认情况下是 origin/<branch_name>),因此无需担心。
附注:您可以在这里找到此 Git 命令的最新版本。欢迎评论和建议。

安装Python来做那些Git本身已经很擅长的事情,不是一个真正的解决方案。更像是一个编程练习。 - Mogens TrasherDK
3
在大多数正常的发行版中,Python已经预装好了。只是使用git的话,你无法:1)自定义输出(例如,使其更加一致)2)以所需的方式组合多个命令 3)轻松地定制逻辑。此外,反复输入相同的命令非常无聊。 - Eugene Yarmash

11

前几种方法对我没用。

假设你有以下分支和远程分支:

Local : Test_Branch
Remote: remotes/origin/feature/Test_FE

为您的本地分支正确设置上游,以跟踪您想要删除的远程分支。

git branch --set-upstream-to=remotes/origin/feature/Test_FE Test_Branch

然后执行以下命令来删除远程分支

git push origin --delete Test_Branch

然后执行以下命令删除本地分支

git branch -D Test_Branch

那就这样了。

git push <remote_name> :<branch_name> 真的不起作用吗?在你的情况下,使用 git push origin :Test_FE。这是11年前发布的最受欢迎、被接受的答案中列出的。 - Andras Deak -- Слава Україні
抱歉,可能应该是 :feature/Test_FE - Andras Deak -- Слава Україні
可能是因为目录的问题,它没有起作用。 使用正确的命名应该可以工作,因为我可以看到点赞数。 但我想分享我所学到的东西。 谢谢。 - sachyy

9

两位作者CoolAJ86apenwarr的答案非常相似。我来回比较了这两个答案,试图理解更好的方法来支持子模块替换。下面是它们的结合体。

首先,在Git Bash中导航到要拆分的Git存储库的根目录。在我的示例中,这是~/Documents/OriginalRepo (master)

# Move the folder at prefix to a new branch
git subtree split --prefix=SubFolderName/FolderToBeNewRepo --branch=to-be-new-repo

# Create a new repository out of the newly made branch
mkdir ~/Documents/NewRepo
pushd ~/Documents/NewRepo
git init
git pull ~/Documents/OriginalRepo to-be-new-repo

# Upload the new repository to a place that should be referenced for submodules
git remote add origin git@github.com:myUsername/newRepo.git
git push -u origin master
popd

# Replace the folder with a submodule
git rm -rf ./SubFolderName/FolderToBeNewRepo
git submodule add git@github.com:myUsername/newRepo.git SubFolderName/FolderToBeNewRepo
git branch --delete --force to-be-new-repo

以下是使用 HTTPS 并更改自定义名称的副本,根文件夹现在为 ~/Documents/_Shawn/UnityProjects/SoProject (master)
# Move the folder at prefix to a new branch
git subtree split --prefix=Assets/SoArchitecture --branch=so-package

# Create a new repository out of the newly made branch
mkdir ~/Documents/_Shawn/UnityProjects/SoArchitecture
pushd ~/Documents/_Shawn/UnityProjects/SoArchitecture
git init
git pull ~/Documents/_Shawn/UnityProjects/SoProject so-package

# Upload the new repository to a place that should be referenced for submodules
git remote add origin https://github.com/Feddas/SoArchitecture.git
git push -u origin master
popd

# Replace the folder with a submodule
git rm -rf ./Assets/SoArchitecture
git submodule add https://github.com/Feddas/SoArchitecture.git
git branch --delete --force so-package

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接