18716

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?

11
  • 1337
    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? Jun 11 '14 at 16:10
  • 68
    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
  • 15
    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. Apr 3 '20 at 20:37
  • 2
    @GabrielStaples Without context, your comment is confusing. Are the "best" rated answers wrong somehow?
    – Nathan
    Jun 19 '20 at 4:32
  • 5
    @Nathan, no, they're not wrong, but they don't teach what you don't know you don't know, whereas the one I link to makes this critical unknown unknown become a known unknown and then a known known. I didn't know you had a 1) local branch, 2) locally-stored remote-tracking branch, and 3) remote branch until I read that answer. Prior to that I thought there was only a local branch and remote branch. The locally-stored remote-tracking branch was an unknown unknown. Making it go from that to a known known is what makes that answer the best. Nov 18 '20 at 23:06

41 Answers 41

1
2
28

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.

2
  • 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
41

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"
2
  • 6
    Be careful with de -D option. In a batch consider using lower -d 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. Mar 5 '17 at 5:45
90

To delete locally - (normal)

git branch -d my_branch

If your branch is in a rebasing/merging progress and that was not done properly, it means you will get an error, Rebase/Merge in progress, so in that case, you won't be able to delete your branch.

So either you need to solve the rebasing/merging. Otherwise, you can do force delete by using,

git branch -D my_branch

To delete in remote:

git push --delete origin my_branch

You can do the same using:

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

Graphical representation:

Enter image description here

1642

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

4
  • 57
    git branch -a will display local and remote branches.It will be help for you diagram introduce. Jul 27 '17 at 3:01
  • 5
    note that if you are setting on the branch you want to delete, you need to checkout a branch other than the one you need to delete (eg: master) before deleting the local branch.
    – BaDr Amer
    May 28 '18 at 8:43
  • When branches get deleted on origin, your local repository won't take notice of that. You'll still have your locally cached versions of those branches (which is actually good) but git branch -a will still list them as remote branches. You can clean up that information locally like this: git remote prune origin Your local copies of deleted branches are not removed by this. The same effect is achieved by using git fetch --prune
    – vibs2006
    May 8 '19 at 6:33
  • 12
    The image is distracting and very large and adds nothing to the answer. I hope this does not become a trend on SO.
    – jmiserez
    Sep 6 '19 at 10:31
20

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
}
55

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
1
  • 3
    I really have no idea why git command is so inconsistent and unintuitive to remember. Looks at the deletion, one is -D, another one is -d|--delete Dec 1 '20 at 9:18
463

It's very simple:

To delete the remote branch

git push -d origin <branch-name>

Or

git push origin :<branch-name>

-- You can also delete tags with this syntax

To forcefully delete local branch

git branch -D <branch-name>

Note: do a git fetch --all --prune on other machines after deleting remote branch, to remove obsolete tracking branches.

Example

to remove local branch

git branch -D my-local-branch

to remove remote branch

git push origin :my-remote-branch
3
  • 11
    I needed to use --delete instead of -d to delete remote branch.
    – ZakJ
    Dec 10 '17 at 23:22
  • 3
    -d option is an alias for --delete and if --delete work then -d should also work, if you forcefully want to delete a branch you can use -D instead of -d or --delete.
    – Vivek Maru
    Dec 18 '17 at 9:48
  • -d does not work for me. The terminal tell me to use -D instead
    – C-Dev
    Sep 2 at 23:25
6

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
12

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.

2
  • Installing Python to do something git does well by itself, is not really a solution. More like an programming exercise. Jan 2 '20 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. Jan 2 '20 at 11:24
6

The first few methods did not work for me,

Lets say you have following branch and remote branch,

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

Set the upstream correctly for your local branch to track the remote branch you want to delete.

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

Then to delete the remote branch execute this

git push origin --delete Test_Branch

Then to delete the local branch execute following command

git branch -D Test_Branch

That's it. Cheers.

3
  • Did git push <remote_name> :<branch_name> really not work? In your case git push origin :Test_FE. That's listed in the top-voted, accepted answer which was posted 11 years ago. Jun 4 at 11:11
  • Sorry, that should probably have been :feature/Test_FE. Jun 4 at 14:25
  • yes. may be because of the directories it did not work. With correct naming it should work as I can see the number of upvotes. But I thought of sharing what I learnt. Thanks
    – sachyy
    Jun 9 at 11:20
3

here you can delete remote branches corresponding to a glob or any branch name:

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

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .