Delete all local git branches
Asked Answered
H

37

698

I follow a development process where I create a new local branch for every new feature or story card. When finished I merge the branch into master and then push.

What tends to happen over time due to a combination of laziness or forgetfulness, is that I end up with a large list of local branches, some of which (such as spikes) may not have been merged.

I know how to list all my local branches and I know how to remove a single branch but I was wondering if there was a git command that allows me to delete all my local branches?

Below is the output of the git branch --merged command.

user@machine:~/projects/application[master]$ git branch --merged
  STORY-123-Short-Description
  STORY-456-Another-Description
  STORY-789-Blah-Blah
* master

All attempts to delete branches listed with grep -v \* (as per the answers below) result in errors:

error: branch 'STORY-123-Short-Description' not found.
error: branch 'STORY-456-Another-Description' not found.
error: branch 'STORY-789-Blah-Blah' not found.

I'm using:

git 1.7.4.1  
ubuntu 10.04  
GNU bash, version 4.1.5(1)-release  
GNU grep 2.5.4  
Hogle answered 15/5, 2012 at 23:45 Comment(3)
Not an answer but one thing to call out, that I often do, is when I reach peak laziness and the local clone is very dirty I simply rm -rf /my_cool_repo and reclone the repo. If I do not have an active branch that is the easiest way to "clean out all local branches" IMO. Clearly not the answer if you are actively doing work on a branch.Niehaus
@Niehaus I wouldn't recommend re-cloning as you'd lose any changes in unversioned and ignored files e.g. IDE projects. The most popular answer below has perfectly worked for me for years.Servo
@louth could you consider to change the accepted answer in order to keep a valid solution ? the current one is no longer workingSelachian
C
805

The 'git branch -d' subcommand can delete more than one branch. So, simplifying @sblom's answer but adding a critical xargs:

git branch -D `git branch --merged | grep -v \* | xargs`

or, further simplified to:

git branch --merged | grep -v \* | xargs git branch -D 

Importantly, as noted by @AndrewC, using git branch for scripting is discouraged. To avoid it use something like:

git for-each-ref --format '%(refname:short)' refs/heads | grep -v "master\|main" | xargs git branch -D

Caution warranted on deletes!

$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
  Story-123-a
  Story-123-b
  Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).
Cyanohydrin answered 16/5, 2012 at 0:43 Comment(14)
This command still reports the same errors as mentioned in the comments for the answer below. error:branch 'STORY-123-Short-Description' not found. for each of the branches listed.Hogle
All the steps you've shown work for me, right up until git branch --merged | grep -v \* | xargs git branch -D and then I get the errors I've shown in the answer.Hogle
So, did using git 1.7.10 solve your problem or do you prefer working directly in the .git repository?Cyanohydrin
If you get a error:branch 'STORY-123-Short-Description' not found. error, this is probably due to the git color settings. This worked for me (note the --no-color option): git branch --no-color --merged | grep -v \* | xargs git branch -DDuo
After a long time, I'm here to share another solution for Node.js developers. github.com/jmlavoier/clear-branches npx clear-branches.Thao
Not an issue in 2012, but these days probably makes sense to use grep -Ev 'main|master' instead, to capture both the common options.Flagstone
Did not work for me. Got the following error: fatal: branch name requiredHypergolic
If your branch has quotes in it, this doesn't workFlessel
How could you make this into an alias for easy use? I tried git config --global alias.dbr "the command..." but I got an error: unknown switch 'v'. This is because this is not a git thing.Word
I copy/pasted the first answer and received Deleted branch master - it did, in fact, delete my master branch. Use caution.Anglofrench
This doesn't work for me. Apparently it adds a question mark to the end of the name of all my branches and then proceeds not to found them, example: branch 'feature1?' not found, when the name of the branch is feature1 error: branch 'add-excel-patologia?' not found. error: branch 'add-excel-read?' not found. error: branch 'add-rotas-prontuario?' not found. error: branch 'db-access?' not found. error: branch 'excel-upload?' not found. error: branch 'remodelagem-paciente?' not found.Emboss
Perhaps show the actual command you used? Or better, create a new question all together.Cyanohydrin
if you're on windows, you can pipe the list of branches to delete to | % {git branch -D $_.Trim() }. so using the above example, git branch -merged | % {git branch -D $_.Trim() } altogether it'd be git branch --merged | % {& {!$_.StartsWith("*") ? "$_.Trim()": $null} }Substitutive
I think git branch | % {& {!$_.StartsWith("*")? "$($_.replace(': ','').Trim())": $null }} | % {git branch -D $_; git push origin --delete $_} is better than my last comment.Substitutive
S
559

The simpler way to delete all branches but keeping others like "develop" and "master" is the following:

git branch | grep -v "develop" | grep -v "master" | grep -v "main" | xargs git branch -D

On windows machines (Powershell)

git branch | %{ $_.Trim() } | ?{ $_ -ne 'master' } | ?{ $_ -ne 'main'} | ?{ $_ -ne 'develop'} | %{ git branch -D $_ }

very useful !

Selachian answered 1/10, 2014 at 23:20 Comment(11)
This answer is clear in piping output from git branch, modifying it, and passing to git branch -D. No need to be mean.Swift
This solution worked for me. Deleted all local branches.Genseric
This will not delete any branch contains word develop or master like 'develop_feature' or 'master_feature'.Maureenmaureene
this wont delete a branch named "developX" (any develop* or master* branches wont be deleted as well)Katherinkatherina
I completely disagree with Andrew C's comment, I am here in 2022 and the solution worked perfectly for me. Thanks geoomAkkadian
This solution worked for me while the accepted answer failed: error: Could not read e5f84685d79b5e263d3b93e13c503735c43a04a8. fatal: revision walk setup failedSalicylate
worked here as well.Cyder
Worked for me also. I don't get what Andrew is talking about. What safety constraints?Manrope
Run this ps script for windows: git branch | %{ $_.Trim() } | ?{ $_ -ne 'master' } | ?{ $_ -ne 'release'} | %{ git branch -D $_ } Skips master and release branchesEudy
this is clearly the best and most readable answer!Schnozzle
This is a good answer, to the point and easy to understand. It is also inclusive. People forget just how many devs work on windows machine.Domain
D
199

I found a nicer way in a comment on this issue on github:

git branch --merged master --no-color | grep -v "master\|stable\|main" | xargs git branch -d

Edit: Added no-color option and excluding of stable branch (add other branches as needed in your case)

Damascene answered 2/9, 2013 at 10:55 Comment(9)
I've tried this but keep getting error: branch 'my-branch-name' not found. for every branch. Using git version 1.8.3.4 (Apple Git-47). Any idea why?Piderit
try 'git branch --merged master | grep -v master | xargs echo' to debug what exactly it is trying to delete? have no better ideas...Damascene
It's something to do with special characters added as part of colour coding. trying all sorts of sed variations to get rid of themPiderit
So. git for-each-ref --format '%(refname:short)' refs/heads/ | grep -v master | xargs git branch -dOrdonnance
@Piderit see the --no-color switch for git branch (edited my response too)Damascene
If you are reading this in 2021. It is likely that you'll encounter fatal: malformed object name master, fatal: branch name required. This is because a lot of github projects don't have a master branch anymore. They often use main instead. In this case, replace the git branch --merged master by git branch --merged main.Thrombophlebitis
I believe it should be -D (capital D)Hearse
@JeffersonLima afaik -D deletes remote branches too. The question was about local branches.Damascene
@Damascene you are right. In fact, the -D option issues a -d -f, i. e. according to the docs "allow deleting the branch irrespective of its merged status, or whether it even points to a valid commit"Hearse
E
176

Parsing the output of git branch is not recommended, and not a good answer for future readers on Stack Overflow.

  1. git branch is what is known as a porcelain command. Porcelain commands are not designed to be machine parsed and the output may change between different versions of Git.
  2. There are user configuration options that change the output of git branch in a way that makes it difficult to parse (for instance, colorization). If a user has set color.branch then you will get control codes in the output, this will lead to error: branch 'foo' not found. if you attempt to pipe it into another command. You can bypass this with the --no-color flag to git branch, but who knows what other user configurations might break things.
  3. git branch may do other things that are annoying to parse, like put an asterisk next to the currently checked out branch

The maintainer of git has this to say about scripting around git branch output

To find out what the current branch is, casual/careless users may have scripted around git branch, which is wrong. We actively discourage against use of any Porcelain command, including git branch, in scripts, because the output from the command is subject to change to help human consumption use case.

Answers that suggest manually editing files in the .git directory (like .git/refs/heads) are similarly problematic (refs may be in .git/packed-refs instead, or Git may change their internal layout in the future).

Git provides the for-each-ref command to retrieve a list of branches.

Git 2.7.X will introduce the --merged option to so you could do something like the below to find and delete all branches merged into HEAD

for mergedBranch in $(git for-each-ref --format '%(refname:short)' --merged HEAD refs/heads/)
do
    git branch -d ${mergedBranch}
done

Git 2.6.X and older, you will need to list all local branches and then test them individually to see if they have been merged (which will be significantly slower and slightly more complicated).

for branch in $(git for-each-ref --format '%(refname:short)' refs/heads/)
do
    git merge-base --is-ancestor ${branch} HEAD && git branch -d ${branch}
done
Edveh answered 2/10, 2014 at 0:1 Comment(12)
git branch --no-color 2>/dev/null?Misteach
It's an improvement for sure. You will always have the problem of needing to filter out the *, and it does amusing things if somebody runs it from detached head. The main problem though is git branch is a porcelain command, and there is no guarantee that the output won't change in some future version of git.Edveh
Thank you @AndrewC - this is both answers the question bout the mysterious "branch not found" errors and provides a working solution using a more appropriate command! 👍Appropriation
How are 'Porcelain' and 'non-Porcelain' GIT commands identified?Cyanohydrin
Man pages for git on Mac OS... how quaint! :-)Cyanohydrin
Probably would be a useful enhancement to exclude 'dev' and 'master' by default?Rewarding
@Rewarding - git branch -d will refuse to delete the currently checked out branch (error: Cannot delete branch 'master' checked out). Any other branch is fair game if it is merged.Edveh
Instead of --merged there is another option --no-merged for other branches, if anyone is looking for it. You will need to use git branch -D ${noMergedBranch} insteadFinsen
Has anyone managed to turn this into a git alias? That would be extremely convenientJuryrig
1. Substitute single quotes for double quotes like this: for mergedBranch in $(git for-each-ref --format "%(refname:short)" --merged HEAD refs/heads/) do git branch -d ${mergedBranch} done 2. git config --global alias.delete-merged-branches 'for mergedBranch in $(git for-each-ref --format "%(refname:short)" --merged HEAD refs/heads/) note: open the single quote but don't close it. This lets you enter more than one line of textJuryrig
@ppicom : an alternative way to aliases is : create a script named git-foo, accessible from your path. git will now execute that script when you invoke git foo.Replace
git checkout @^0; git for-each-ref --merged --format='delete %(refname)' refs/heads | git update-ref --stdin; git will re-set-up any remote branches you check out.Runnel
I
140

Try the following shell command:

git branch | grep -v "master" | xargs git branch -D

Explanation:

  • Get all branches (except for the master) via git branch | grep -v "master" command
  • Select every branch with xargs command
  • Delete branch with xargs git branch -D
Inhalator answered 27/9, 2019 at 17:52 Comment(5)
Although this may be a correct answer. One line of code isn't very useful without an explanation of what and how it solves the original question. Please provide details to your answer.Superintend
How to delete all other branches except master and some other branch say branchA using this one line command? Currently I do git branch | grep -v "master" | grep -v "branchA" | xargs git branch -DMarchelle
I would also put a git checkout master in front: git checkout master; git branch | grep -v "master" | xargs git branch -DPavyer
Why do I get errors like these? error: branch '<branch-name>' not found. These branches exist on local that's why it is trying to find them...Likable
add "--force" at the end if you really mean it.Rajasthani
C
74

The below command will delete all the local branches except master branch.

git branch | grep -v "master" | xargs git branch -D

The above command

  1. list all the branches
  2. From the list ignore the master branch and take the rest of the branches
  3. delete the branch
Cockle answered 24/8, 2018 at 14:8 Comment(3)
I would use git branch | grep -v "master" | xargs git branch -d first so I don't delete unmerged branches, just to be safe. But nice answer!Worser
Here is a powershell version ,@(git branch | Select-String -Pattern "[^(*?)\s? master]") | ForEach-Object{$_.Line.Trim()} | %{git branch -D $_}Worser
@baklazan this would only work in Windows 10 command line if you have some tools installed. You probably have MINGW or some other such thing and you don't know it.Languish
T
70

To delete every branch except the one that you currently have checked out:

for b in `git branch --merged | grep -v \*`; do git branch -D $b; done

I would recommend changing git branch -D $b to an echo $b the first few times to make sure that it deletes the branches that you intend.

Tuberculous answered 15/5, 2012 at 23:50 Comment(6)
with this command I get error:branch 'a_branch_name' not found. I can see what you're trying to do and I've been playing around with the command but for some reason git doesn't seem to like the branch names supplied...Hogle
hmmm. to help troubleshoot, it would be useful to see some example output from git branch --mergedTuberculous
my branch names are of the format STORY-123-Short-DescriptionHogle
and when you run git branch --merged, you get a list with one of those on each line?Tuberculous
does it literally say error:branch 'a_branch_name' not found.? Or does it complain about one of the branch names from your git branch output above?Tuberculous
it says error:branch 'STORY-123-Short-Description' not found. for each of the branches listed above.Hogle
M
50

To delete all local branches in linux except the one you are on

// hard delete

git branch -D $(git branch)
Mcdougald answered 5/4, 2019 at 7:54 Comment(2)
This one feels safer than going into .git and removing stuff.Petra
This command very usefulRabblerousing
A
43

Just a note, I would upgrade to git 1.7.10. You may be getting answers here that won't work on your version. My guess is that you would have to prefix the branch name with refs/heads/.

CAUTION, proceed with the following only if you made a copy of your working folder and .git directory.

I sometimes just go ahead and delete the branches I don't want straight from .git/refs/heads. All these branches are text files that contain the 40 character sha-1 of the commit they point to. You will have extraneous information in your .git/config if you had specific tracking set up for any of them. You can delete those entries manually as well.

Atmospheric answered 16/5, 2012 at 2:4 Comment(3)
This will not work if you have packed refs, or even if you cloned from a remote server sometimes (which will provide you packed files). If you refs are packed, then the refs will not be stored in .git/refs/heads, they will be stored in a file called "packed-refs". See git-scm.com/docs/git-pack-refs.Manganin
It seems like a bad idea to remove the branch you have checked out at the momentDestalinization
@Destalinization Just checkout a commit beforehand, and your detached HEAD will float all right.Cariole
P
29

I found it easier to just use text editor and shell.

  1. Type git checkout <TAB> in shell. Will show all local branches.
  2. Copy them to a text editor, remove those you need to keep.
  3. Replace line breaks with spaces. (In SublimeText it's super easy.)
  4. Open shell, type git branch -D <PASTE THE BRANCHES NAMES HERE>.

That's it.

Pease answered 1/8, 2013 at 22:9 Comment(2)
I don't think you can remove the branch which you are stand on.Pauiie
@Dong There's a * beside that branch so you just remove it from the copied list!Abm
B
27

first (switch to the branch you want to keep > ex: master):

git checkout master

second (make sure you are on master)

git branch -D $(git branch)

If you're using PowerShell, use

git branch -D $(git branch).Trim()
Bacardi answered 11/10, 2022 at 7:9 Comment(2)
git branch -D $(git branch) works just as I want. Thanks!Kozhikode
Additionally run git fetch --prune to delete any ghost remote branches from terminal and as well vscode historyPsychotherapy
B
21

From Windows Command Line, delete all except the current checked out branch using:

for /f "tokens=*" %f in ('git branch ^| find /v "*"') do git branch -D %f
Behnken answered 8/2, 2019 at 1:6 Comment(3)
on windows 10, when I put this in a .bat or .cmd file, it says: f was unexpected at this time. Do, I need to change something about the %f parameters ?Pash
From a .cmd file, you need to replace %f with %%fBehnken
Just for reference, this will delete all branches containing "chore": for /f "tokens=*" %f in ('git branch ^| find "chore"') do git branch -D %fIndistinct
S
20

If you want to delete all your local branches, here is the simple command:

git branch -D `git branch`

Note: This will delete all the branches except the current checked out branch

Subinfeudate answered 16/12, 2020 at 16:19 Comment(0)
R
18

To remove all your local git branches but keep main

git branch | grep -v "main" | xargs git branch -D 
Rimarimas answered 6/4, 2022 at 8:55 Comment(1)
One slight problem with this is that if you are currently on one of the non-main branches you will get an asterisk in the list of branches to delete.Mafalda
A
16

I had a similar kind of situation and recently found the following command useful.

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep>/) printf "%s", $0 }'`

If you want to keep multiple branches, then

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep1>|<Branch_You_Want_to_Keep2>/) printf "%s", $0 }'`

hope this helps someone.

Arcuation answered 12/7, 2013 at 7:23 Comment(1)
Nice one but I needed backticks to get it to work git branch -D `git branch | awk '{ if ($0 !~ /master/) printf "%s", $0 }'` --Actually I think you did have them originally but they got lost in the SO formatting.Clematis
S
15

Here's the Powershell solution for anyone running on a Windows machine

git checkout master # by being on the master branch, you won't be able to delete it
foreach($branch in (git branch))
{
    git branch -D $branch.Trim()
}
Shoup answered 25/2, 2021 at 22:24 Comment(1)
I remove all my features with foreach($branch in (git branch)) { if ($branch.trim().startswith("feature")) {git branch -D $branch.trim()} }. Thank you :)Gynecology
F
15

Delete All Local Branches in Local


Use this as this is pretty simple. This will delete all the branches on your computer and not on remote repository.

 git branch -D $(git branch) 
Flite answered 22/3, 2023 at 8:48 Comment(2)
FYI this only works in Linux on Windows see https://mcmap.net/q/13643/-delete-all-local-git-branchesDeckard
Worked perfectly on mac. Nice and simple. Thanks.Ingenuity
S
13

If you work with NodeJS, I wrote this command:

npx git-clear-branch

The command clears all of your local branch except master and current branch.

Spouse answered 10/2, 2021 at 6:36 Comment(0)
D
11
git branch -l |grep -v master | xargs git branch -D

But what care deleting branch ; just remove the workspace and re clone it if it t is a small repository !!

Devries answered 8/9, 2021 at 5:18 Comment(0)
S
9

Although this isn't a command line solution, I'm surprised the Git GUI hasn't been suggested yet.

I use the command line 99% of the time, but in this case its either far to slow (hence the original question), or you don't know what you are about to delete when resorting to some lengthy, but clever shell manipulation.

The UI solves this issue since you can quickly check off the branches you want removed, and be reminded of ones you want to keep, without having to type a command for every branch.

From the UI go to Branch --> Delete and Ctrl+Click the branches you want to delete so they are highlighted. If you want to be sure they are merged into a branch (such as dev), under Delete Only if Merged Into set Local Branch to dev. Otherwise, set it to Always to ignore this check.

GitUI: delete local branches

Spasmodic answered 8/8, 2018 at 19:41 Comment(0)
H
7

If you don't need to go through Git itself, you can also delete heads under .git/refs/heads manually or programmatically. The following should work with minimal tweaking under Bash:

shopt -s extglob
rm -rf .git/refs/heads/!(master)

This will delete every local branch except your master branch. Since your upstream branches are stored under .git/refs/remotes, they will remain untouched.

If you are not using Bash, or want to recurse a lot of Git repositories at once, you can do something similar with GNU find:

find . \
    -path remotes -path logs -prune -o \
    -wholename \*.git/refs/heads/\* \! -name master -print0 |
xargs -0 rm -rf

The find solution is probably more portable, but pruning paths and filenames is tricky and potentially more error-prone.

Hudnut answered 16/5, 2012 at 2:34 Comment(0)
W
7

None of the answers satisfied my needs fully, so here we go:

git branch --merged | grep -E "(feature|bugfix|hotfix)/" | xargs git branch -D && git remote prune origin

This will delete all local branches which are merged and starting with feature/, bugfix/ or hotfix/. Afterwards the upstream remote origin is pruned (you may have to enter a password).

Works on Git 1.9.5.

Womble answered 29/12, 2014 at 10:23 Comment(0)
P
7

If you want to keep master, develop and all remote branches. Delete all local branches which are not present on Github anymore.

$ git fetch --prune

$ git branch | grep -v "origin" | grep -v "develop" | grep -v "master" | xargs git branch -D

1] It will delete remote refs that are no longer in use on the remote repository.

2] This will get list of all your branches. Remove branch containing master, develop or origin (remote branches) from the list. Delete all branches in list.

Warning - This deletes your own local branches as well. So do this when you have merged your branch and doing a cleanup after merge, delete.

Proctoscope answered 9/12, 2020 at 6:13 Comment(0)
N
6

Based on a combination of a number of answers here - if you want to keep all branches that exist on remote but delete the rest, the following oneliner will do the trick:

git for-each-ref --format '%(refname:short)' refs/heads | grep -Ev `git ls-remote --quiet --heads origin | awk '{print substr($2, 12)}'| paste -sd "|" -` | xargs git branch -D
Nitrogen answered 27/3, 2019 at 6:34 Comment(0)
S
4

git branch -d [branch name] for local delete

git branch -D [branch name] also for local delete but forces it

Scale answered 5/9, 2020 at 14:41 Comment(0)
C
4

Deleting many local branches at once

# delete all local unmerged branches
git branch --no-merged | egrep -v "(^\*|master|dev)" | xargs git branch -D
# delete all local branches (merged and unmerged).
git branch | egrep -v "(^\*|master|dev)" | xargs git branch -D  

Deleting remote branches

# Deleting non-existent tracking branches
git remote prune <remote> --dry-run
# Deleting a single remote branch
git push <remote> --delete <branch>
# Deleting many remote branches at once
git branch -r --merged | egrep -v "(^\*|master|dev)" | sed 's/origin\///' | xargs -n 1 git push origin --delete

Source

Cannae answered 12/5, 2021 at 0:51 Comment(0)
B
4
git for-each-ref --format="%(if) %(HEAD) %(then) %(else) %(refname:short) %(end)" refs/heads/ | xargs -r git branch -D

This:

  1. Doesn't use a porcelain git branch
  2. Uses the official (from [git-for-each-ref](https://git-scm.com/docs/git-for-each-ref help page) way of identifying the current branch

Parts:

  1. git for-each-ref --format="..." refs/heads/ finds all branches that are not the current branch
    • %(HEAD) finds if the branch is the current branch so "%(if) %(HEAD) %(then) %(else) %(refname:short) %(end) prints an empty line for the current branch. From help:
      • We ignore space when evaluating the string before %(then), this is useful when we use the %(HEAD) atom which prints either "*" or " " and we want to apply the if condition only on the HEAD ref.

    • %(refname:short) -from help:
      • For a non-ambiguous short name of the ref append :short.

  2. xargs -r git branch -D deletes the branch
    • -r, or --no-run-if-empty, makes the xarg ignore the empty line for the current branch
Bentz answered 5/1 at 2:18 Comment(0)
E
3

If you are using windows, try this in powershell

git branch | Select-String -notmatch "master" | ForEach-Object {$_.ToString().Trim()} | ForEach-Object {git branch -D $_}
Envision answered 2/3, 2023 at 3:36 Comment(0)
T
2

For powershell, this will work:

git branch --format '%(refname:lstrip=2)' --merged `
    | Where-Object { $_ -ne 'master' } `
    | ForEach-Object { git branch -d $_ }
Toulon answered 1/8, 2019 at 17:29 Comment(0)
C
2

I don't have grep or other unix on my box but this worked from VSCode's terminal:

git branch -d $(git branch).trim()

I use the lowercase d so it won't delete unmerged branches.

I was also on master when I did it, so * master doesn't exist so it didn't attempt deleting master.

Corymb answered 8/4, 2020 at 19:5 Comment(1)
Confirmed: If not on master, this command WILL delete master.Catalyst
O
2

I recommend a more moderate answer. Many of the answers here use -D which is forced delete regardless of whether changes have been merged or not. Here is a one liner which leaves untouched the branches which have un-merged changes.

git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d

Or you can try other examples listed but just change the -D to -d. I know the OP asked how to delete, but in most use cases, its safer to use -d.

Oliva answered 23/2, 2021 at 2:47 Comment(0)
I
2
git branch | grep release-1.4 | xargs -n 1 -I % sh -c 'git branch -D %'

Easy way to delete all the branches with a name that matches the pattern 'release-1.4*'. I also use it periodically with ticket prefixes to delete all my local working branches, but leave pipeline branches unbothered.

Improvident answered 20/10, 2022 at 18:0 Comment(0)
T
1

The following script deletes branches. Use it and modify it at your own risk, etc. etc.

Based on the other answers in this question, I ended up writing a quick bash script for myself. I called it "gitbd" (git branch -D) but if you use it, you can rename it to whatever you want.

gitbd() {
if [ $# -le 1 ]
  then
    local branches_to_delete=`git for-each-ref --format '%(refname:short)' refs/heads/ | grep "$1"`
    printf "Matching branches:\n\n$branches_to_delete\n\nDelete? [Y/n] "
    read -n 1 -r # Immediately continue after getting 1 keypress
    echo # Move to a new line
    if [[ ! $REPLY == 'N' && ! $REPLY == 'n' ]]
      then
        echo $branches_to_delete | xargs git branch -D
    fi
else
  echo "This command takes one arg (match pattern) or no args (match all)"
fi
}

It will offer to delete any branches which match a pattern argument, if passed in, or all local branches when called with with no arguments. It will also give you a confirmation step, since, you know, we're deleting things, so that's nice.

It's kind of dumb - if there are no branches that match the pattern, it doesn't realize it.

An example output run:

$ gitbd test
Matching branches:

dummy+test1
dummy+test2
dummy+test3

Delete? [Y/n] 
Tactician answered 7/11, 2014 at 1:2 Comment(0)
H
1

I wrote a shell script in order to remove all local branches except develop

branches=$(git branch | tr -d " *")
output=""
for branch in $branches 
do
  if [[ $branch != "develop" ]]; then
    output="$output $branch"
  fi
done
git branch -d $output
Hypotenuse answered 12/7, 2018 at 4:4 Comment(0)
B
1

Above answers works fine. Here is another approach when we have lot of branches in local repo and we have to delete many branches except few which are lying in local machine.

First git branch will list all the local branches.

To transpose the column of branch names into single row in file by running a unix command
git branch > sample.txt
This will save it in sample.txt file. And run
awk 'BEGIN { ORS = " " } { print }' sample.txt
command in shell. This will transform the column to row and copy the list of branch names in single row.

And then run
git branch -D branch_name(s).
This will delete all listed branches present in local

Brae answered 28/9, 2018 at 6:57 Comment(0)
C
1

For this purpose, you can use git-extras

$ git delete-merged-branches
Deleted feature/themes (was c029ab3).
Deleted feature/live_preview (was a81b002).
Deleted feature/dashboard (was 923befa).
Chaotic answered 12/9, 2019 at 17:3 Comment(0)
B
1

For anyone who wants a windows Command Prompt solution:

Delete all branches other than master:

FOR /f "tokens=*" %i IN ('git branch ^| findstr /v "master"') DO git branch -d %i

Delete all branches with any string matches in the branch name:

FOR /f "tokens=*" %i IN ('git branch ^| findstr "TargetName"') DO git branch -d %i

Three things to note:

  1. git branch -d will only delete branches that have been merged. If you want to delete branches regardless of whether they've been merged or not, you can use git branch -D instead.
  2. It will not delete the branch you are currently checking out.
  3. If you want to put this command into a batch file, you need to double the % signs. This is a quirk of batch file scripting where % signs are treated as special characters and need to be escaped by doubling them.
Bligh answered 10/6, 2023 at 0:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.