17987

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?

Matthew Rankin
  • 400,554
  • 38
  • 116
  • 156
  • 1219
    ***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
  • 60
    Note: for Git 2.5+ (Q2 2015), the exact message will be "**`deleted remote-tracking branch`**": see https://github.com/git/git/commit/ccd593cffaa020ff767860ec211462b8dbd727a6#diff-d18f86ea14e2f1e5bff391b2e54438cbR268 – 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: https://www.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
  • @Adam: 81. 42 answers were deleted for various reasons. The public's unexplained obsession with a particular topic is one of life's greatest mysteries. – Robert Harvey Nov 30 '19 at 15:21
  • 7
    Skip the first few answers and just jump down to the best one: https://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 03 '20 at 20:37
  • 2
    @GabrielStaples Without context, your comment is confusing. Are the "best" rated answers wrong somehow? – Nathan Jun 19 '20 at 04:32
  • 3
    @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. – Gabriel Staples Nov 18 '20 at 23:06
  • I wanted to add a note that one cannot delete a branch on which one is currently working upon. I have made this rookie mistake so thought if this could help. :) – cRAN Feb 09 '21 at 14:28
  • Ordinary user note: If you intend to upvote Robert Harvey's comment, do note that there are already 1215 upvotes added. Will your new upvote add any substantial value? :) ...Now it's 1216! That is a *lot*. – Panzercrisis May 26 '21 at 00:41

39 Answers39

22603

Executive Summary

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

Note that in most cases the remote name is origin. In such a case you'll have to use the command like so.

$ git push -d origin <branch_name>

Delete Local Branch

To delete the local branch use one of the following:

$ git branch -d branch_name
$ git branch -D branch_name

Note: The -d option is an alias for --delete, which only deletes the branch if it has already been fully merged in its upstream branch. You could also use -D, which is an alias for --delete --force, which deletes the branch "irrespective of its merged status." [Source: man git-branch]
Also note that git branch -d branch_name will fail if you are currently in the branch you want to remove. The message starts with error: Cannot delete the branch 'branch_name'. If so, first switch to some other branch, for example: git checkout main.

Delete Remote Branch [Updated on 8-Sep-2017]

As of Git v1.7.0, you can delete a remote branch using

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

which might be easier to remember than

$ git push <remote_name> :<branch_name>

which was added in Git v1.5.0 "to delete a remote branch or a tag."

Starting on Git v2.8.0 you can also use git push with the -d option as an alias for --delete.

Therefore, the version of Git you have installed will dictate whether you need to use the easier or harder syntax.

Delete Remote Branch [Original Answer from 5-Jan-2010]

From Chapter 3 of Pro Git by Scott Chacon:

Deleting Remote Branches

Suppose you’re done with a remote branch — say, you and your collaborators are finished with a feature and have merged it into your remote’s main branch (or whatever branch your stable code-line is in). You can delete a remote branch using the rather obtuse syntax git push [remotename] :[branch]. If you want to delete your server-fix branch from the server, you run the following:

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

Boom. No more branches on your server. You may want to dog-ear this page, because you’ll need that command, and you’ll likely forget the syntax. A way to remember this command is by recalling the git push [remotename] [localbranch]:[remotebranch] syntax that we went over a bit earlier. If you leave off the [localbranch] portion, then you’re basically saying, “Take nothing on my side and make it be [remotebranch].”

I issued git push origin: bugfix and it worked beautifully. Scott Chacon was right—I will want to dog ear that page (or virtually dog ear by answering this on Stack Overflow).

Then you should execute this on other machines

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

to propagate changes.

Junaid
  • 3,203
  • 1
  • 23
  • 31
Matthew Rankin
  • 400,554
  • 38
  • 116
  • 156
  • 407
    Don't forget to do a `git fetch --all --prune` on other machines after deleting the remote branch on the server. ||| After deleting the local branch with `git branch -d` and deleting the remote branch with `git push origin --delete` other machines may still have "obsolete tracking branches" (to see them do `git branch -a`). To get rid of these do `git fetch --all --prune`. – Trevor Boyd Smith May 27 '15 at 16:51
  • 14
    in addition to @TrevorBoydSmith's `git branch -a` to view all branches, you can also use `git branch -r` to view remote branches only. see also `git remote show origin` - source: http://gitready.com/intermediate/2009/02/13/list-remote-branches.html – Sandra Sep 09 '15 at 09:53
  • 19
    I had to run `git branch -D Branch_Name` to get rid of the local branch – Kolob Canyon Mar 10 '16 at 01:32
  • 11
    @KolobCanyon You only have to use -D if the branch has not been merged into another branch. – BTRUE Apr 05 '16 at 16:27
  • 4
    The question was ***"What do I need to do differently to successfully delete the remotes/origin/bugfix branch both locally and on GitHub?"*** After running the commands in your updated answer, the local branch is still present. It would be nice if the accepted answer was a ***complete*** answer. Its absolutely amazing at how difficult Git makes simple tasks... – jww Jun 07 '16 at 02:15
  • Really appreciate the executive summary at the beginning. I'll add that I also had to change the second command to `-D` to confirm I wanted to delete while there were unmerged changes. – Jordan Gray Jan 04 '17 at 15:33
  • 1
    I am getting `error: Cannot delete the branch '19_jan_improvements_post_v1' which you are currently on.` when I am trying to delete a local branch, which I am working on that branch. I am not able to checkout to a different branch also, because I have to merge some files and so it gives this error - `error: you need to resolve your current index first`. What to do if I just don't care about merging those files and anyway want to get rid of the local branch. – Sandeepan Nath Jan 19 '17 at 10:00
  • 3
    Doesn't work if you in the branch. Need to to do a git checkout master or whatever to get out of the branch prior. – Kelly May 16 '17 at 03:08
  • To better understand the git push origin : syntax, go to https://stackoverflow.com/questions/1519006/how-do-you-create-a-remote-git-branch – Alex Aug 16 '17 at 14:27
  • Note that the `-d` as an alias for `--delete` also works with the push call. So `git push origin -d ` works too – Sheldon Aug 24 '17 at 12:13
  • Why do I need to specify remote when pushing? – Alex78191 Sep 19 '17 at 00:46
  • @Alex78191 Because you may not want to push your branch to all your remotes. However I use this alias when I want to push all my branch to all my remotes. https://stackoverflow.com/a/18674313/1308453 – Philip Rego Oct 26 '17 at 20:38
  • @Sheldon Which git version are you using? For me (git 2.7.4) `-d` is not working for `push`. – luator Dec 01 '17 at 14:57
  • @luator I am using 2.8.1, and my apologies, `-d` as an alias for `--delete` was added in 2.8.0, see here: https://legacy-developer.atlassian.com/blog/2016/03/whats-new-in-git-2.8/ – Sheldon Dec 01 '17 at 16:53
  • You can use source tree tool as well if you don't want to remember git commands. – user1101733 Feb 22 '18 at 14:42
  • Only `$ git push :` worked for me. – Christophe Roussy May 22 '18 at 14:44
  • The `--delete` might be easier to remember, but it's too late if you already understand the `push remote :deadbr`, plus the cute thing about the latter is that it also works for tags. – Alois Mahdal Jul 09 '18 at 21:52
  • 1
    In the executive summary you have `git push --delete ` but in the first "Delete Remote Branch Update" section you have `git push --delete `. i.e. The parameters are in a different order. Can I suggest making these the same to avoid confusion please. – Caltor Nov 29 '18 at 11:28
  • I ran the first line of the executive summary and the second wasn't "needed"(?). The branch is gone both locally and remotely. – Daniel Springer Dec 27 '18 at 15:28
  • @DanielSpringer That shouldn't be the case. It will delete the remote branch `origin/mybranch` in your repo and on the server, but it won't delete any local tracking branches (`mybranch`). – Timmmm Jan 24 '19 at 17:01
  • @Timmmm either I ran it before and forgot, or... I don’t know :P – Daniel Springer Jan 24 '19 at 17:17
  • Note that this can fail with `! [remote rejected] (refusing to delete the current branch: refs/heads/)` `error: failed to push some refs to 'git@github.com:/.git'` if you have set this branch in Github as your default branch. If you have, go to your project in Github -> "Settings" -> "Branches" and then change your Default Branch to another. Then repeating your command to delete the branch will work. – stwr667 Feb 14 '19 at 08:08
  • This answer shows how to delete a branch on a specific remote. For consistency, the prune step should also be limited to that specific remote. Drop the `--all` option and specify the remote: `git fetch --prune `. – Robin A. Meade Sep 20 '19 at 20:45
  • This can be piped into other commands like grep to filter out branches you do not want to delete `git branch --merged | grep -v "\$BRANCHNAME\b" | xargs git branch -d` – Andy Macleod May 06 '20 at 10:45
  • I just wanted to remove an entry from the `git remote -v` list (I correct: 2 entries, namely the upstream ones) and came across this post. Well my solution is to remove the **remote branch** from `.git/config` editing this file. I added them by accident with `git remote add ..` – Timo Nov 21 '20 at 10:50
  • If the repository is deleted and you need to delete the local branch tracking the remote branch, use `git branch -d -r /` – Dror Bar Jan 28 '21 at 14:00
  • Is it necessary to push changes after deleting a remote branch? – a.ak Mar 02 '21 at 13:06
3457

Matthew's answer is great for removing remote branches and I also appreciate the explanation, but to make a simple distinction between the two commands:

To remove a local branch from your machine:

git branch -d {the_local_branch} (use -D instead to force deleting the branch without checking merged status)

To remove a remote branch from the server:

git push origin --delete {the_remote_branch}

Reference: Git: Delete a branch (local or remote)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Eric Brotto
  • 49,233
  • 29
  • 122
  • 171
  • 260
    @megido well `-D` force deletes, `-d` gives you a warning if it's not already merged in. – TankorSmash Nov 06 '14 at 19:04
  • 8
    If your local branch is not merge with master and ran `'git branch -d your_branch` then you will error like `error: The branch 'your_branch' is not fully merged. If you are sure you want to delete it, run 'git branch -D your_branch'.` – geeks Oct 31 '15 at 12:59
  • 14
    I would suggest using -d instead of -D because it is safer. If -d fails due to unmerged commits then you need to assess that and if it is definitely OK to remove then use -D. – rooby Feb 02 '16 at 03:47
  • 7
    Others with repository clones where remote branches have been removed should run `git remote prune ` (e.g. `git remote prune origin`) in order to locally remove stale branches that no longer exist in the remote. – code_dredd Apr 18 '16 at 23:07
  • If your branch in your fork (not always origin), use the proper repository. e.g. git push myRepo :mrbranchtodelete – Dhanuka777 May 19 '16 at 00:53
  • 3
    I would like to add that -d gives a warning if it isn't merged in with the current HEAD. If you need clarity I recommend this command `git branch -a --merged origin/master` It will list any branches, both local and remote; that have been merged into master. [Additional information here](http://stackoverflow.com/questions/226976/how-can-i-know-in-git-if-a-branch-has-been-already-merged-into-master) – Eric Feb 10 '17 at 13:10
  • @Eric-Brotto For your answer to be complete, you need to add the `git fetch -p` command to fetch changes on other machines – SebMa Mar 22 '20 at 20:54
  • > well -D force deletes, -d gives you a warning if it's not already merged in. \n\n Pretty bad naming if you ask me. Should be -df or -d --force. – Charming Robot Jul 05 '20 at 13:45
  • If the repository is deleted and you need to delete the local branch tracking the remote branch, use `git branch -d -r /` – Dror Bar Jan 28 '21 at 14:00
2173

The short answers

If you want more detailed explanations of the following commands, then see the long answers in the next section.

Deleting a remote branch

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

Deleting a local branch

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

Deleting a local remote-tracking branch

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

The long answer: there are three different branches to delete!

When you're dealing with deleting branches both locally and remotely, keep in mind that there are three different branches involved:

  1. The local branch X.
  2. The remote origin branch X.
  3. The local remote-tracking branch origin/X that tracks the remote branch X.

Visualization of three branches

The original poster used:

git branch -rd origin/bugfix

Which only deleted his local remote-tracking branch origin/bugfix, and not the actual remote branch bugfix on origin.

Diagram 2

To delete that actual remote branch, you need

git push origin --delete bugfix

Diagram 3

Additional details

The following sections describe additional details to consider when deleting your remote and remote-tracking branches.

Pushing to delete remote branches also removes remote-tracking branches

Note that deleting the remote branch X from the command line using a git push will also remove the local remote-tracking branch origin/X, so it is not necessary to prune the obsolete remote-tracking branch with git fetch --prune or git fetch -p. However, it wouldn't hurt if you did it anyway.

You can verify that the remote-tracking branch origin/X was also deleted by running the following:

# 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

Pruning the obsolete local remote-tracking branch origin/X

If you didn't delete your remote branch X from the command line (like above), then your local repository will still contain (a now obsolete) remote-tracking branch origin/X. This can happen if you deleted a remote branch directly through GitHub's web interface, for example.

A typical way to remove these obsolete remote-tracking branches (since Git version 1.6.6) is to simply run git fetch with the --prune or shorter -p. Note that this removes all obsolete local remote-tracking branches for any remote branches that no longer exist on the remote:

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

Here is the relevant quote from the 1.6.6 release notes (emphasis mine):

"git fetch" learned --all and --multipleoptions, to run fetch from many repositories, and --prune option to remove remote tracking branches that went stale. These make "git remote update" and "git remote prune" less necessary (there is no plan to remove "remote update" nor "remote prune", though).

Alternative to above automatic pruning for obsolete remote-tracking branches

Alternatively, instead of pruning your obsolete local remote-tracking branches through git fetch -p, you can avoid making the extra network operation by just manually removing the branch(es) with the --remote or -r flags:

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

See Also

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • From your illustration, I can see there are local clone repo and remote origin repo. So there are at least two physical branches. Where is the third branch to delete? Is the third branch only a pointer pointing to a commit in the local clone repo? – huggie Feb 18 '16 at 02:00
  • 6
    @huggie that's pretty much correct. Branches in Git are just bookmarks attached to commits. So in my graphs above, there are `X` and `origin/X` bookmarks in the local clone (2 branches), and then there is `X` on the remote (making 3 branches). –  Feb 23 '16 at 07:33
  • 7
    +1 for the remote tracking branch. This branch is what causes issues when you clone someone else's branch. It keeps on tracking your commits and asking you if you want to push to that person's branch. – Kermit_ice_tea Jun 21 '17 at 19:48
  • 1
    For the sake of future readers: What @Kermit_ice_tea is talking about above is a *local branch* (as described in this answer), not a *remote-tracking branch*. When a *local branch* has an "upstream branch" configured for it, it will by default pull from and push to that remote branch. A *local branch* that has an "upstream branch" set on it is [referred to as a "tracking branch"](https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches#_tracking_branches), so it's easy to confuse with *remote-tracking branches* due to the similar terminology. – David P Mar 05 '20 at 11:21
  • 3
    I've read all the answers down to here and this is for sure the best answer I've read so far!--(and probably the best one on this page, period). This is especially true because it's the only answer which states this REALLY IMPORTANT fact that I never knew before: "**there are 3 different branches to delete!**" I had no idea! This all makes so much more sense now, and it sheds so much light on all the other answers here now too. Thanks! – Gabriel Staples Apr 03 '20 at 20:35
  • What happens if you run `git fetch --prune`, withOUT specifying the remote branch? Does it prune all remotes? – Gabriel Staples Jan 05 '21 at 00:08
  • It should be noted that running `git push origin --delete `, as far as I can tell, ALSO deletes the locally-stored remote-tracking branch named `origin/branch`. So, **to delete the remote branch AND locally-stored remote-tracking branch in one command, just use `git push origin --delete `.** Then, you just need to delete the local branch with `git branch -D branch`. That covers the deletion of all 3 branches with only 2 commands. – Gabriel Staples Jan 05 '21 at 00:40
1594

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Alireza
  • 83,698
  • 19
  • 241
  • 152
  • 53
    `git branch -a` will display local and remote branches.It will be help for you diagram introduce. – LoranceChen Jul 27 '17 at 03:01
  • 4
    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 08: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 08 '19 at 06:33
  • 10
    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 06 '19 at 10:31
833

You can also use the following to delete the remote branch

git push --delete origin serverfix

Which does the same thing as

git push origin :serverfix

but it may be easier to remember.

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
pagetribe
  • 14,073
  • 3
  • 22
  • 18
387

Tip: When you delete branches using

git branch -d <branchname> # Deletes local branch

or

git push origin :<branchname> # Deletes remote branch

only the references are deleted. Even though the branch is actually removed on the remote, the references to it still exists in the local repositories of your team members. This means that for other team members the deleted branches are still visible when they do a git branch -a.

To solve this, your team members can prune the deleted branches with

git remote prune <repository>

This is typically git remote prune origin.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
pfrenssen
  • 5,140
  • 1
  • 19
  • 15
  • 14
    You should clarify that the above `git push` operation deletes the local branch *and* the remote branch. – Annika Backstrom May 21 '13 at 13:51
  • 22
    Note that `git remote prune` is a somewhat obsolete way to remove obsolete remote-tracking branches, the newer way to do it is to use `git fetch --prune` or `git fetch -p`. –  Jun 11 '14 at 16:30
  • 1
    @RRMadhav, indeed you won't see the deleted branch after deleting it since the reference to the remote branch will be removed for you locally. Anyone else on your team that has checked out that branch will still have that reference and will still see it unless they prune the branch. – pfrenssen Dec 05 '14 at 14:27
375

If you want to delete a branch, first checkout to the branch other than the branch to be deleted.

git checkout other_than_branch_to_be_deleted

Deleting the local branch:

git branch -D branch_to_be_deleted

Deleting the remote branch:

git push origin --delete branch_to_be_deleted
Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
Praveen Hiremath
  • 4,029
  • 2
  • 15
  • 10
331

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.

Happy Coding :)

Vivek Maru
  • 4,527
  • 1
  • 16
  • 26
  • 8
    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 09:48
272
git branch -D <name-of-branch>
git branch -D -r origin/<name-of-branch>
git push origin :<name-of-branch>
Felipe
  • 15,458
  • 9
  • 63
  • 87
233

This is simple: Just run the following command:

To delete a Git branch both locally and remotely, first delete the local branch using this command:

git branch -d example

(Here example is the branch name.)

And after that, delete the remote branch using this command:

git push origin :example
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Syeful Islam
  • 3,403
  • 1
  • 16
  • 18
209

Another approach is:

git push --prune origin

WARNING: This will delete all remote branches that do not exist locally. Or more comprehensively,

git push --mirror

will effectively make the remote repository look like the local copy of the repository (local heads, remotes and tags are mirrored on remote).

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
imanuelcostigan
  • 3,109
  • 3
  • 15
  • 18
  • 1
    git push --prune origin didn't do anything for me on gitlab: git clone git://repo.git; git branch -d -r origin/some-branches; git push --prune origin; yields: Everything up-to-date; git fetch; brings locally deleted branches back; git push --mirror; now they are really gone! – eMBee Oct 08 '15 at 16:46
176

I use the following in my Bash settings:

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

Then you can call:

git-shoot branchname
Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
crizCraig
  • 7,169
  • 4
  • 46
  • 50
  • 11
    I ended up just add the alias "shoot" into my .gitconfig shoot = push origin --delete – hdost Dec 04 '14 at 18:06
  • If your origin is a Atlassian Stash and the branch is set as the default, you will get an error "By default, deleting the current branch is denied...". I had to change the default branch in Stash to point to another branch before I could delete. – neoscribe Dec 12 '14 at 00:29
  • This is perfectly simple as you've done it, but fyi git also lets you make custom commands. Put `git push origin --delete $1` in a file on your path called `git-shoot` and `git shoot branchname` will work too. – mahemoff Oct 14 '15 at 07:09
  • this is a good solution – yourson Jan 01 '21 at 04:41
140

Delete locally:

To delete a local branch, you can use:

git branch -d <branch_name>

To delete a branch forcibly, use -D instead of -d.

git branch -D <branch_name>

Delete remotely:

There are two options:

git push origin :branchname

git push origin --delete branchname

I would suggest you use the second way as it is more intuitive.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Rahul Gupta
  • 39,529
  • 10
  • 89
  • 105
138

If you want to complete both these steps with a single command, you can make an alias for it by adding the below to your ~/.gitconfig:

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

Alternatively, you can add this to your global configuration from the command line using

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

NOTE: If using -d (lowercase d), the branch will only be deleted if it has been merged. To force the delete to happen, you will need to use -D (uppercase D).

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ryan Kohn
  • 11,921
  • 10
  • 50
  • 80
  • 6
    This is what I was looking for. My own shell function alias didn't work (Unexpected EOF) and I couldn't figure out why, but this works great! The only change I made was replacing `&&` with `;` so that even if the first command fails the second will still execute (sometimes only local or only remote exists). – user1021726 Dec 16 '14 at 08:55
137

Since January 2013, GitHub included a Delete branch button next to each branch in your "Branches" page.

Relevant blog post: Create and delete branches

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
Nacho Coloma
  • 6,009
  • 2
  • 36
  • 42
  • 3
    I only started using Github this year, so I was wondering why this was such a highly rated question, and why none of the top answers were suggesting to just delete it from the Github web interface! Interesting that it's only a recent addition. – Cam Jackson Sep 11 '13 at 12:18
  • 6
    I was going to point this one out. Note that the button won't delete your local branch... see this answer for how to do that: http://stackoverflow.com/a/10999165/901641 – ArtOfWarfare Oct 29 '13 at 14:02
121

To delete your branch locally and remotely

  • Checkout to master branch - git checkout master

  • Delete your remote branch - git push origin --delete <branch-name>

  • Delete your local branch - git branch --delete <branch-name>

dippas
  • 49,171
  • 15
  • 93
  • 105
mfathy00
  • 1,521
  • 1
  • 11
  • 26
118

You can also do this using git remote prune origin

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

It prunes and deletes remote-tracking branches from a git branch -r listing.

Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
nickleefly
  • 3,543
  • 1
  • 24
  • 31
114

In addition to the other answers, I often use the git_remote_branch tool. It's an extra install, but it gets you a convenient way to interact with remote branches. In this case, to delete:

grb delete branch

I find that I also use the publish and track commands quite often.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
u2622
  • 2,892
  • 3
  • 22
  • 26
106

A one-liner command to delete both local, and remote:

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

Or add the alias below to your ~/.gitconfig. Usage: git kill branch-name

[alias]
    kill = "!f(){ git branch -D \"$1\";  git push origin --delete \"$1\"; };f"
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Vinnie James
  • 4,816
  • 4
  • 33
  • 47
  • 20
    ⚠️ Use `git branch -D` carefully in a script, since it force-deletes a branch without checking it has been merged. Use `-d` to be safe. – caesarsol Mar 13 '17 at 14:05
98

Deleting Branches

Let's assume our work on branch "contact-form" is done and we've already integrated it into "master". Since we don't need it anymore, we can delete it (locally):

$ git branch -d contact-form

And for deleting the remote branch:

git push origin --delete contact-form
Community
  • 1
  • 1
Ulysses Alves
  • 1,960
  • 1
  • 18
  • 32
91

Delete remote branch

git push origin :<branchname>

Delete local branch

git branch -D <branchname>

Delete local branch steps:

  1. checkout to another branch
  2. delete local branch
jayxhj
  • 2,104
  • 17
  • 22
90

Simply say:

git branch -d <branch-name>
git push origin :<branch-name>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
piyushmandovra
  • 3,673
  • 2
  • 17
  • 29
  • This works if its your own branch. But if you are pruning all unneeded branches in the repo (some of which aren't yours) it wouldn't suffice – Kermit_ice_tea Jun 30 '16 at 22:23
87
git push origin --delete <branch Name>

is easier to remember than

git push origin :branchName
Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
Smila
  • 1,082
  • 8
  • 16
86

Now you can do it with the GitHub Desktop application.

After launching the application

  1. Click on the project containing the branch
  2. Switch to the branch you would like to delete

    Switching branch

  3. From the "Branch" menu, select, "Unpublish...", to have the branch deleted from the GitHub servers.

    Unpublish branch

  4. From the "Branch" menu, select, 'Delete "branch_name"...', to have the branch deleted off of your local machine (AKA the machine you are currently working on)

    Delete local branch

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Eric
  • 6,347
  • 5
  • 37
  • 61
  • 15
    I didn't downvote, but my thinking is that it isn't substantively helping. The question is obviously asking for a more commandline type answer without having to use an external program, if people were clicking into here, they likely won't be looking for a github for desktop ways. – Daemedeor Nov 06 '15 at 11:51
  • 12
    @Daemedeor , I dissagree. In 2010 when the OP asked the question, the UI way of doing it didn't exist and the only option was command line. To indicate that you want a command line only option it should be stated in the question or with the tag, [tag:command-line-interface], which in this case is no present. – Eric Nov 06 '15 at 16:00
  • 3
    The git command for deleting a remote branch sucks and I tend to forget it (both new and old). Luckily there are GUI tools that have the option. Git Gui, TortoiseGit and GitHub Desktop have it - I wish Git Extensions had this functionality too. Anyway, what I remember is to start Git Gui from within Git Extensions when I need to delete a remote branch. – vezenkov Mar 25 '16 at 21:59
85

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Mohideen bin Mohammed
  • 14,471
  • 7
  • 86
  • 95
75

This won't work if you have a tag with the same name as the branch on the remote:

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

In that case you need to specify that you want to delete the branch, not the tag:

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

Similarly, to delete the tag instead of the branch you would use:

git push origin :refs/tags/branch-or-tag-name
Serving Quarantine period
  • 66,345
  • 10
  • 43
  • 85
Greg
  • 7,624
  • 4
  • 33
  • 50
  • 1
    This is fine, but people really shouldn't be naming their branches and tags with the same name and same naming scheme in the first place. –  Jul 29 '14 at 10:00
  • 3
    Well, my scenario was that I was converting a branch to a tag and it made sense for the tag to have the same name as the branch. By converting I mean merging branch B to A and tagging the last commit in branch B with tag B so that after deleting branch B it can still be easily restored by simply checking out tag B. – Greg Jul 30 '14 at 11:59
  • [More](https://stackoverflow.com/a/7303710/1705829) on the `:` and why it `deletes` – Timo Apr 12 '21 at 18:50
  • I get still the same error `error: failed to push some refs to 'https://github.com/tik9/tik9.github.io'` when `git push origin :refs/heads/main`. Probably `github` is the culprit. – Timo Apr 12 '21 at 18:52
57

Many of the other answers will lead to errors/warnings. This approach is relatively fool proof although you may still need git branch -D branch_to_delete if it's not fully merged into some_other_branch, for example.

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

Remote pruning isn't needed if you deleted the remote branch. It's only used to get the most up-to-date remotes available on a repository you're tracking. I've observed git fetch will add remotes, not remove them. Here's an example of when git remote prune origin will actually do something:

User A does the steps above. User B would run the following commands to see the most up-to-date remote branches:

git fetch
git remote prune origin
git branch -r
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Brandon Cook
  • 1,272
  • 11
  • 11
55

I got sick of googling for this answer, so I took a similar approach to the answer that crizCraig posted earlier.

I added the following to my Bash profile:

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

Then every time I'm done with a branch (merged into master, for example) I run the following in my terminal:

gitdelete my-branch-name

...which then deletes my-branch-name from origin as as well as locally.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
arthurakay
  • 5,261
  • 7
  • 37
  • 57
  • 7
    expanding on this, `--delete "$@"` and `-D "$@"` instead of `$1` will handle it for multiple branches. – kunl Jun 27 '16 at 13:15
  • 4
    I suggest running `git branch -d` (with lowercase 'd') first to ensure changes have been merged, and then push if successful (put `&&` in between commands) – bryn Jul 19 '16 at 14:17
53

Use:

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

If you are sure you want to delete it, run

git branch -D bugfix

Now to clean up deleted remote branches run

git remote prune origin
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user
  • 699
  • 1
  • 6
  • 21
53

Before executing

git branch --delete <branch>

make sure you determine first what the exact name of the remote branch is by executing:

git ls-remote

This will tell you what to enter exactly for <branch> value. (branch is case sensitive!)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jbooker
  • 4,227
  • 1
  • 30
  • 43
50

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
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
KARTHIKEYAN.A
  • 11,752
  • 4
  • 81
  • 93
46

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
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dan Rosenstark
  • 64,546
  • 54
  • 267
  • 405
  • @chhh then you need to extend this functionality to make this a variable instead of an assumption. – Dan Rosenstark Dec 05 '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: http://stackoverflow.com/questions/2342894/why-and-when-to-use-shell-instead-of-ruby, where this topic has been discarded as opinion-based by SO. – Dan Rosenstark May 21 '15 at 20:03
  • 5
    @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
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"
Jared Knipp
  • 5,606
  • 7
  • 42
  • 48
  • 6
    Be careful with de `-D` option. In a batch consider using lower `-d` – Alwin Kesler Mar 04 '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](https://git-scm.com/docs/git-branch#git-branch--d) before deleting, using `-D` forces the branch deletion. – Jared Knipp Mar 05 '17 at 05:45
35

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Bradley Flood
  • 8,235
  • 2
  • 41
  • 41
32

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
levi
  • 19,165
  • 7
  • 56
  • 68
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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Uchiha Itachi
  • 1,140
  • 1
  • 15
  • 37
  • 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 01 '17 at 09:00
  • `git branch --delete ` doesn't delete a remote branch, you need `git push --delete ` to do that – Sheldon Aug 24 '17 at 12:15
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
}
Vagelis Prokopiou
  • 1,237
  • 12
  • 13
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.

Eugene Yarmash
  • 119,667
  • 33
  • 277
  • 336
  • Installing **Python** to do something **git** does well by itself, is not really a solution. More like an programming exercise. – Mogens TrasherDK Jan 02 '20 at 03: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 02 '20 at 11:24
7

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
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
ShawnFeatherly
  • 1,862
  • 19
  • 17