繁体   English   中英

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

[英]How do I delete a Git branch locally and remotely?

尝试删除远程分支失败:

$ 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分支?

执行摘要

$ git push -d <remote_name> <branchname> $ git branch -d <branchname>

注意:在大多数情况下, <remote_name>将是origin

删除本地分支

要删除本地分支,请使用以下方法之一:

 $ git branch -d <branch_name> $ git branch -D <branch_name>
  • -d选项是--delete的别名,它仅在分支已经完全合并到其上游分支时才删除该分支。
  • -D选项是--delete --force的别名,它删除“无论其合并状态如何”的分支。 [来源: man git-branch ]
  • Git v2.3开始, git branch -d (删除)学会了遵守-f (强制)标志。
  • 如果您尝试删除当前选定的分支,您将收到错误消息。

删除远程分支

Git v1.7.0 开始,您可以使用删除远程分支

$ git push <remote_name> --delete <branch_name>

这可能比记住更容易

$ git push <remote_name>:<branch_name>

Git v1.5.0中添加“删除远程分支或标签”。

Git v2.8.0开始,您还可以使用git push-d选项作为--delete的别名。 因此,您安装的 Git 版本将决定您是否需要使用更简单或更难的语法。

删除远程分支 [2010 年 1 月 5 日的原始答案]

来自 Scott Chacon 的Pro Git的第 3 章:

删除远程分支

假设你完成了一个远程分支——比如说,你和你的合作者完成了一个特性,并将它合并到远程的主分支(或者你的稳定代码行所在的任何分支)。 您可以使用相当钝的语法git push [remotename]:[branch]删除远程分支。 如果要从服务器中删除 server-fix 分支,请运行以下命令:

 $ git push origin:serverfix To git@github.com:schacon/simplegit.git - [deleted] serverfix

繁荣。 您的服务器上没有更多分支。 您可能想对这个页面进行狗耳朵,因为您将需要该命令,并且您可能会忘记语法。 记住这个命令的一种方法是回顾我们之前讨论过的git push [remotename] [localbranch]:[remotebranch]语法。 如果您[localbranch]部分,那么您基本上是在说,“我这边什么都不做,让它成为[remotebranch] 。”

我发布了git push origin: bugfix并且效果很好。 Scott Chacon 是对的——我会想在那个页面上狗耳朵(或者实际上通过在 Stack Overflow 上回答这个问题来狗耳朵)。

然后你应该在其他机器上执行这个

# Fetch changes from all remotes and locally delete # remote deleted branches/tags etc # --prune will do the job:-; git fetch --all --prune

传播更改。

马修的回答非常适合删除远程分支,我也很欣赏解释,但要对这两个命令做一个简单的区分:

要从您的机器中删除本地分支

git branch -d {the_local_branch} (使用-D代替强制删除分支而不检查合并状态)

要从服务器中删除远程分支

git push origin --delete {the_remote_branch}

参考: Git:删除分支(本地或远程)

简短的答案

如果您想对以下命令进行更详细的解释,请参阅下一节中的长答案。

删除远程分支

git push origin --delete <branch> # Git version 1.7.0 or newer git push origin -d <branch> # Shorter version (Git 1.7.0 or newer) git push origin:<branch> # Git versions older than 1.7.0

删除本地分支

git branch --delete <branch> git branch -d <branch> # Shorter version git branch -D <branch> # Force-delete un-merged branches

删除本地远程跟踪分支

git branch --delete --remotes <remote>/<branch> git branch -dr <remote>/<branch> # Shorter git fetch <remote> --prune # Delete multiple obsolete remote-tracking branches git fetch <remote> -p # Shorter

长答案:要删除三个不同的分支

当您在本地和远程处理删除分支时,请记住涉及三个不同的分支

  1. 本地分支X
  2. 远程源分支X
  3. 跟踪远程分支X的本地远程跟踪分支origin/X X 。

三个分支的可视化

使用的原始海报:

 git branch -rd origin/bugfix

这只删除了他的本地远程跟踪分支origin/bugfix ,而不是origin上的实际远程分支bugfix

图 2

要删除那个实际的远程分支,您需要

git push origin --delete bugfix

图 3

额外细节

以下部分描述了删除远程和远程跟踪分支时要考虑的其他详细信息。

推送删除远程分支也会删除远程跟踪分支

请注意,使用git push从命令行删除远程分支X也将删除本地远程跟踪分支origin/X ,因此没有必要使用git fetch --prunegit fetch -p --prune 修剪过时的远程跟踪分支git fetch -p 但是,无论如何,如果您这样做,也不会受到伤害。

您可以通过运行以下命令来验证远程跟踪分支origin/X是否也被删除:

 # View just remote-tracking branches git branch --remotes git branch -r # View both strictly local as well as remote-tracking branches git branch --all git branch -a

修剪过时的本地远程跟踪分支 origin/X

如果您没有从命令行中删除远程分支X (如上),那么您的本地存储库仍将包含(现在已过时)远程跟踪分支origin/X 例如,如果您直接通过 GitHub 的 web 接口删除了远程分支,就会发生这种情况。

删除这些过时的远程跟踪分支(自 Git 版本 1.6.6 起)的典型方法是使用--prune或更短的-p简单地运行git fetch 请注意,这会删除远程上不再存在的任何远程分支的所有过时的本地远程跟踪分支

 git fetch origin --prune git fetch origin -p # Shorter

以下是1.6.6 发行说明中的​​相关引用(重点是我的):

“git fetch” 学习了--all--multiple选项,从许多存储库运行 fetch,以及--prune选项来删除过时的远程跟踪分支。 这些使“git remote update”和“git remote prune”变得不那么必要(虽然没有计划删除“remote update”或“remote prune”)。

对过时的远程跟踪分支进行上述自动修剪的替代方案

或者,不要通过git fetch -p修剪过时的本地远程跟踪分支,您可以通过使用--remotes-r标志手动删除分支来避免进行额外的网络操作

 git branch --delete --remotes origin/X git branch -dr origin/X # Shorter

也可以看看

Steps for deleting a branch:

For deleting the remote branch:

git push origin --delete <your_branch>

For deleting the local branch, you have three ways:

1: git branch -D <branch_name>

2: git branch --delete --force <branch_name>  # Same as -D

3: git branch --delete  <branch_name>         # Error on unmerge

Explain: OK, just explain what's going on here!

Simply do git push origin --delete to delete your remote branch only, add the name of the branch at the end and this will delete and push it to remote at the same time...

Also, git branch -D, which simply delete the local branch only!...

-D stands for --delete --force which will delete the branch even it's not merged (force delete), but you can also use -d which stands for --delete which throw an error respective of the branch merge status...

I also create the image below to show the steps:

Delete a remote and local branch in git

您还可以使用以下内容删除远程分支

git push --delete origin serverfix

哪个做同样的事情

git push origin:serverfix

但它可能更容易记住。

这很简单:

删除远程分支

git push -d origin <branch-name>

或者

git push origin:<branch-name>

-- 你也可以用这种语法删除标签

强制删除本地分支

git branch -D <branch-name>

注意:删除远程分支后,在其他机器上执行git fetch --all --prune ,以删除过时的跟踪分支。

例子

删除本地分支

git branch -D my-local-branch

删除远程分支

git push origin:my-remote-branch

提示:如果你想查看所有可用的分支,你可以使用git branch -a

并且只查看远程分支,您可以使用git branch -r

提示:当您使用删除分支时

git branch -d <branchname> # Deletes local branch

或者

git push origin:<branchname> # Deletes remote branch

只有引用被删除。 即使分支实际上已在远程删除,对它的引用仍然存在于团队成员的本地存储库中。 这意味着对于其他团队成员,当他们执行git branch -a时,删除的分支仍然可见。

为了解决这个问题,您的团队成员可以使用

git remote prune <repository>

这通常是git remote prune origin

如果要删除一个分支,首先checkout到要删除的分支以外的分支。

 git checkout other_than_branch_to_be_deleted

删除本地分支:

 git branch -D branch_to_be_deleted

删除远程分支:

 git push origin --delete branch_to_be_deleted
 git branch -D <name-of-branch> git branch -D -r origin/<name-of-branch> git push origin:<name-of-branch>

这很简单:只需运行以下命令:

要在本地和远程删除 Git 分支,首先使用以下命令删除本地分支:

 git branch -d example

(这里的example是分支名称。)

之后,使用以下命令删除远程分支:

 git push origin:example

另一种方法是:

 git push --prune origin

警告:这将删除本地不存在的所有远程分支。 或者更全面地说,

 git push --mirror

将有效地使远程存储库看起来像存储库的本地副本(本地头、远程和标签在远程上镜像)。

我在Bash设置中使用以下内容:

 alias git-shoot="git push origin --delete"

然后你可以调用:

 git-shoot branchname

本地删除:

要删除本地分支,您可以使用:

 git branch -d <branch_name>

要强制删除分支,请使用-D而不是-d

 git branch -D <branch_name>

远程删除:

有两种选择:

 git push origin:branchname git push origin --delete branchname

我建议您使用第二种方式,因为它更直观。

如果您想使用单个命令完成这两个步骤,您可以通过将以下内容添加到您的~/.gitconfig来为其创建别名:

 [alias] rmbranch = ";f(){ git branch -d ${1} && git push origin --delete ${1}; } f"

或者,您可以使用命令行将其添加到全局配置中

git config --global alias.rmbranch \ ';f(){ git branch -d ${1} && git push origin --delete ${1}; } f'

注意:如果使用-d (小写 d),只有合并后的分支才会被删除。 要强制删除,您需要使用-D (大写 D)。

自 2013 年 1 月起,GitHub 在“分支”页面中的每个分支旁边都包含一个删除分支按钮。

相关博文:创建和删除分支

在本地和远程删除您的分支

  • 结帐到主分支 - git checkout master

  • 删除您的远程分支 - git push origin --delete <branch-name>

  • 删除本地分支 - git branch --delete <branch-name>

您也可以使用git remote prune origin来执行此操作

$ git remote prune origin Pruning origin URL: git@example.com/yourrepo.git * [pruned] origin/some-branchs

它从git branch -r列表中修剪和删除远程跟踪分支。

除了其他答案,我经常使用git_remote_branch工具。 这是一个额外的安装,但它为您提供了一种与远程分支交互的便捷方式。 在这种情况下,要删除:

 grb delete branch

我发现我也经常使用publishtrack命令。

删除本地和远程的单行命令:

 D=branch-name; git branch -D $D; git push origin:$D

或者将下面的别名添加到您的~/.gitconfig中。 用法: git kill branch-name

 [alias] kill = ";f(){ git branch -D \"$1\"; git push origin --delete \"$1\"; } f"

删除分支

假设我们在分支“contact-form”上的工作已经完成,并且我们已经将它集成到“master”中。 由于我们不再需要它,我们可以(在本地)删除它:

 $ git branch -d contact-form

对于删除远程分支:

 git push origin --delete contact-form

删除远程分支

git push origin:<branchname>

删除本地分支

git branch -D <branchname>

删除本地分支步骤:

  1. 结帐到另一个分支
  2. 删除本地分支

简单地说:

 git branch -d <branch-name> git push origin:<branch-name>

本地删除 - (正常)

 git branch -d my_branch

如果您的分支处于 rebase/merge 进度并且没有正确完成,则意味着您将收到错误Rebase/Merge in progress ,因此在这种情况下,您将无法删除您的分支。

所以要么你需要解决变基/合并。 否则,您可以使用强制删除

 git branch -D my_branch

远程删除:

 git push --delete origin my_branch

您可以使用以下方法执行相同操作:

 git push origin:my_branch # Easy to remember both will do the same.

图示:

在此处输入图像描述

 git push origin --delete <branch Name>

比记忆更容易

git push origin:branchName

现在您可以使用GitHub 桌面应用程序来做到这一点。

启动应用程序后

  1. 单击包含分支的项目
  2. 切换到您要删除的分支

    切换分支

  3. 从“分支”菜单中,select,“取消发布...”,从 GitHub 服务器中删除分支。

    取消发布分支

  4. 从“分支”菜单select ,“删除”分支名称“...”,将分支从本地计算机(也就是您当前正在使用的计算机)中删除

    删除本地分支

如果您有一个与远程分支同名的标签,这将不起作用:

 $ git push origin:branch-or-tag-name error: dst refspec branch-or-tag-name matches more than one. error: failed to push some refs to 'git@github.com:SomeName/some-repo.git'

在这种情况下,您需要指定要删除分支,而不是标签:

 git push origin:refs/heads/branch-or-tag-name

同样,要删除标签而不是您将使用的分支:

 git push origin:refs/tags/branch-or-tag-name

许多其他答案将导致错误/警告。 这种方法是相对简单的,尽管你可能仍然需要git branch -D branch_to_delete如果它没有完全合并到some_other_branch中,例如。

 git checkout some_other_branch git push origin:branch_to_delete git branch -d branch_to_delete

如果您删除了远程分支,则不需要远程修剪。 它仅用于获取您正在跟踪的存储库上可用的最新远程。 我观察到git fetch将添加遥控器,而不是删除它们。 这是git remote prune origin实际执行某些操作的示例:

用户 A 执行上述步骤。 用户 B 将运行以下命令来查看最新的远程分支:

 git fetch git remote prune origin git branch -r

我厌倦了在谷歌上搜索这个答案,所以我对 crizCraig 之前发布的答案采取了类似的方法。

我将以下内容添加到我的 Bash 配置文件中:

 function gitdelete(){ git push origin --delete $1 git branch -D $1 }

然后每次我完成一个分支(例如合并到master )时,我都会在我的终端中运行以下命令:

 gitdelete my-branch-name

...然后从origin和本地删除my-branch-name

根据使用终端的最新文档,我们可以通过以下方式删除。

本地删除:

 git branch -D usermanagement

远程删除:

 git push --delete origin usermanagement

利用:

 git push origin:bugfix # Deletes remote branch git branch -d bugfix # Must delete local branch manually

如果您确定要删除它,请运行

git branch -D bugfix

现在清理已删除的远程分支运行

git remote prune origin

执行前

git branch --delete <branch>

确保首先通过执行以下命令确定远程分支的确切名称:

git ls-remote

这将告诉您准确输入<branch>值的内容。 branch区分大小写!)

这是所有其他答案的混搭。 它需要 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

我将以下别名添加到我的.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"

用于删除远程分支的命令行的替代选项是GitHub 分支页面

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

在 GitHub 存储库的Code -> Branches页面中找到。

我自己通常更喜欢命令行,但这个GitHub 页面向您展示了有关分支的更多信息,例如最后更新日期和用户,以及前后提交的数量 它在处理大量分支时很有用。

有很好的答案,但是,如果你有大量的分支,在本地和远程一个一个地删除它们,将是一项乏味的任务。 您可以使用此脚本自动执行这些任务。

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 分支

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

git branch --delete <branch>

或者

-

在 GitHub 桌面应用程序中,当您签出分支后,您可以通过分支菜单条删除本地分支:

在此处输入图像描述

如果您使用 GitHub 桌面应用程序,而是使用 Visual Studio 之类的 IDE 进行本地源代码控制,您只需执行几个快速步骤:

  1. 签出您要删除的分支以外的分支。
  2. 右键单击要删除的分支。
  3. 从上下文菜单中选择删除选项。

然后,在线登录到您的 GitHub 帐户后,转到存储库并单击“所有分支”选项卡。 从那里,只需单击要删除的分支名称右侧的小垃圾桶图标。

在此处输入图像描述

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

我在 .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
}

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

#!/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> ),因此无需关心。

PS 你可以在这里找到这个 Git 命令的最新版本。 欢迎提出意见和建议。

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

前几种方法对我不起作用。

假设您有以下分支和远程分支,

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

而已。

在这里,您可以删除对应于 glob 或任何分支名称的远程分支:

git branch -r --list "origin/*" | xargs git branch -r -D

简而言之——

git branch -d {branchName}

这将在本地删除分支。 然后

git push origin -d {branchName}

这将意味着远程删除操作。 如果要在本地删除分支,请使用大写“D”,例如在本地删除分支-

git branch -D {branchName}

只需确保分支已合并和/或准备删除。 然后去头做。

$git branch -d <branch name>
// Locally, use -D to force delete
$git push origin :<branch name>
// Remote delete your branch
// Also can be done in the Repo manually

注意:如果你需要在删除后恢复你的分支 [👉][https://stackoverflow.com/questions/1992364/git-recover-deleted-remote-branch]

许多其他答案将导致错误/警告。 根据使用终端的最新文档,我们可以通过以下方式将其删除:

// delete branch locally
git branch -d localBranchName

// delete branch remotely
git push origin --delete remoteBranchName

推荐步骤

  1. 删除所有本地标签 $git tag -d $(git tag -l)

  2. 获取所有远程标签 $git fetch 检索所有远程标签,为您提供远程标签的完整列表。

  3. 删除所有远程标签 $git push origin --delete $(git tag -l) 参考本地列表删除远程标签。

  4. 删除所有本地标签 $git tag -d $(git tag -l) 再次删除所有本地标签。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM