17021

I want to delete a branch both locally and remotely.

Failed Attempts to Delete a Remote Branch

$ 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.

What should I do differently to successfully delete the remotes/origin/bugfix branch both locally and remotely?

  • 1065
    Moderator note: If you intend to answer this question, do note that there are already 40 answers posted. Will your new answer add any substantial value? – Robert Harvey Jun 11 '14 at 16:10
  • 54
    Note: for Git 2.5+ (Q2 2015), the exact message will be "deleted remote-tracking branch": see github.com/git/git/commit/… – VonC May 25 '15 at 14:57
  • You may be interested in this script which simplifies the difference between deleting a local branch AND a remote one: tlbx.app/blog/delete-any-git-branch-the-easy-way – Mig Sep 12 '19 at 10:11
  • @RobertHarvey only 39 now – Adam Nov 28 '19 at 18:57
  • 2
    Skip the first few answers and just jump down to the best one: stackoverflow.com/a/23961231/4561887. To delete a git branch, there are actually 3 different branches to delete! This answer makes that fact clear. – Gabriel Staples Apr 3 at 20:37

40 Answers 40

1
2
43
0

Here is a mashup of all the other answers. It requires Ruby 1.9.3+ and is tested only on OS X.

Call this file git-remove, make it executable, and put it in your path. Then use, for example, 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
| improve this answer | |
  • @chhh then you need to extend this functionality to make this a variable instead of an assumption. – Dan Rosenstark Dec 5 '14 at 16:44
  • 3
    sorry, but install Ruby for that kind of work ? More logical is implementation on bash, which will work out of box. – Reishin May 21 '15 at 19:37
  • 1
    @Reishin Ruby is installed on the box just like Bash, at least on OSX. Please see: stackoverflow.com/questions/2342894/…, where this topic has been discarded as opinion-based by SO. – Dan Rosenstark May 21 '15 at 20:03
  • 4
    @Yar this link is out of the context and have a more broader scope. I tell only about git and as topic is not originated only for OSX, that choose is strange for other systems (e.g. *UNIX, Windows) – Reishin May 21 '15 at 20:33
39
0

I added the following aliases to my .gitconfig file. This allows me to delete branches with or without specifying the branch name. Branch name is defaulted to the current branch if no argument is passed in.

[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"
| improve this answer | |
  • 6
    Be careful with de -D option. In a batch consider using lower -d – Alwin Kesler Mar 4 '17 at 11:41
  • In my case, I'm almost always deleting after merging (or without the need to merge). Using lower -d will require the branch be merged before deleting, using -D forces the branch deletion. – Jared Knipp Mar 5 '17 at 5:45
32
0

An alternative option to the command line for deleting remote branches is the GitHub branches page.

See for example: https://github.com/angular/angular.js/branches

Found in the Code -> Branches page of a GitHub repository.

I generally prefer command line myself but this GitHub page shows you lots more information about the branches, such as last updated date and user, and number of commits ahead and behind. It is useful when dealing with a large number of branches.

| improve this answer | |
32
0

According to the latest document using a terminal we can delete in the following way.

Delete in local:

git branch -D usermanagement

Delete in remote location:

git push --delete origin usermanagement
| improve this answer | |
31
0

I also had similar issues, and the following seems to work:

This deletes the local branch:

git branch -d the_local_branch

This removes the remote branch

git push origin :the_remote_branch

Source: Makandra Cards

| improve this answer | |
31
0

There are good answers, but, in case that you have a ton of branches, deleting them one by one locally and remotely, would be a tedious tasks. You can use this script to automate these tasks.

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
  • List the branches that you don't want to delete
  • Iterate over the remote's branches and if they aren't in our "preserve list", deleted them.

Source: Removing Git branches at once

| improve this answer | |
  • How do I run this script? Thanks – patricK Mar 28 '19 at 12:02
26
0

Using Git Bash you can execute the following:

git branch --delete <branch>

Or

-

From the GitHub desktop application, when you have the branch checked out, you can delete the local branch via the Branch menu strip:

Enter image description here

If you are not using the GitHub desktop application and are using an IDE like Visual Studio for your local source control, all you have to do is a couple of quick steps:

  1. Check out a branch other than the one you wish to delete.
  2. Right-click the branch you wish to delete.
  3. Select the Delete option from the context menu.

Then, once logged in to your GitHub account online, go to the repository and click the All Branches tab. From there, just click the little trash can icon on the right on the name of the branch you wish to delete.

Enter image description here

*Keep in mind - if the branch isn't published, there isn't any need to try to delete it from your online repository.

| improve this answer | |
  • I don't see these Overview, Yours, Active, State and All branches tab on GitHub website. Looks like this is an old snapshot. Under the Code tab, I see sub-tabs like commits, branches, releases and contributors. When I am the owner of a repository then I see an additional tab named MIT. – RBT Aug 1 '17 at 9:00
  • git branch --delete <branch> doesn't delete a remote branch, you need git push <server> --delete <branch> to do that – Sheldon Aug 24 '17 at 12:15
19
0

I created the following convenient function in my .bash_aliases file:

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
}
| improve this answer | |
11
0

The most flexible way is to use a custom Git command. For example, create the following Python script somewhere in your $PATH under the name git-rmbranch and make it executable:

#!/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))

Then git rmbranch -h will show you usage information:

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

Note that git push origin --delete <branch_name> also removes the local remote-tracking branch (origin/<branch_name> by default), so no need to care about that.

P.S. You can find the latest version of this Git command here. Comments and suggestions are welcome.

| improve this answer | |
  • Installing Python to do something git does well by itself, is not really a solution. More like an programming exercise. – Mogens TrasherDK Jan 2 at 3:19
  • 3
    @Mogens Python is already preinstalled in most sane distributions. With git only you can't for example: 1) customize the output (e.g. make it more consistent) 2) combine multiple commands in desired way 3) easily customize the logic. Besides, entering the same commands over and over again is pretty boring. – Eugene Yarmash Jan 2 at 11:24
4
0

Both CoolAJ86's and apenwarr's answers are very similar. I went back and forth between the two trying to understand the better approach to support a submodule replacement. Below is a combination of them.

First navigate Git Bash to the root of the Git repository to be split. In my example here that is ~/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

Below is a copy of above with the customize-able names replaced and using HTTPS instead. The root folder is now ~/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
| improve this answer | |
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.