How can I delete all Git branches which have been merged?
I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?
git github version-control branch feature-branch
add a comment |
I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?
git github version-control branch feature-branch
35
git branch -D deletes branches that have NOT been merged! Use with care!
– Dan Solovay
Dec 23 '16 at 14:05
27
To be slightly more specificgit branch -Ddeletes any branch whether it as been merged or not.
– PhilT
Feb 8 '17 at 9:48
6
You can also do this directly from GitHub, if you go to the 'branches' section of your repo (e.g. github.com/<username>/<repo_name>/branches). There should be a list of all your branches, with a red trashcan icon on the side which will delete the selected branch. Much faster than doing it in the terminal! Will also show how far ahead/behindmastereach branch is. However, your local client will still list the old branches if you rungit branch -a; usegit fetch --pruneto remove them (as per this answer ).
– user5359531
Feb 24 '17 at 16:13
2
Script to do this locally or remotely - with safety checks and pre-configured "safe branches": github.com/fatso83/dotfiles/tree/master/utils/…git delete-merged --doit originorgit delete-merged --doit --local
– oligofren
Jun 27 '17 at 15:10
You could also use this app to auto delete merged branches.
– Sebass van Boxel
Aug 7 '18 at 16:16
add a comment |
I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?
git github version-control branch feature-branch
I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?
git github version-control branch feature-branch
git github version-control branch feature-branch
edited Aug 31 '17 at 23:49
Peter Mortensen
13.7k1986112
13.7k1986112
asked May 25 '11 at 15:54
NyambaaNyambaa
13k82532
13k82532
35
git branch -D deletes branches that have NOT been merged! Use with care!
– Dan Solovay
Dec 23 '16 at 14:05
27
To be slightly more specificgit branch -Ddeletes any branch whether it as been merged or not.
– PhilT
Feb 8 '17 at 9:48
6
You can also do this directly from GitHub, if you go to the 'branches' section of your repo (e.g. github.com/<username>/<repo_name>/branches). There should be a list of all your branches, with a red trashcan icon on the side which will delete the selected branch. Much faster than doing it in the terminal! Will also show how far ahead/behindmastereach branch is. However, your local client will still list the old branches if you rungit branch -a; usegit fetch --pruneto remove them (as per this answer ).
– user5359531
Feb 24 '17 at 16:13
2
Script to do this locally or remotely - with safety checks and pre-configured "safe branches": github.com/fatso83/dotfiles/tree/master/utils/…git delete-merged --doit originorgit delete-merged --doit --local
– oligofren
Jun 27 '17 at 15:10
You could also use this app to auto delete merged branches.
– Sebass van Boxel
Aug 7 '18 at 16:16
add a comment |
35
git branch -D deletes branches that have NOT been merged! Use with care!
– Dan Solovay
Dec 23 '16 at 14:05
27
To be slightly more specificgit branch -Ddeletes any branch whether it as been merged or not.
– PhilT
Feb 8 '17 at 9:48
6
You can also do this directly from GitHub, if you go to the 'branches' section of your repo (e.g. github.com/<username>/<repo_name>/branches). There should be a list of all your branches, with a red trashcan icon on the side which will delete the selected branch. Much faster than doing it in the terminal! Will also show how far ahead/behindmastereach branch is. However, your local client will still list the old branches if you rungit branch -a; usegit fetch --pruneto remove them (as per this answer ).
– user5359531
Feb 24 '17 at 16:13
2
Script to do this locally or remotely - with safety checks and pre-configured "safe branches": github.com/fatso83/dotfiles/tree/master/utils/…git delete-merged --doit originorgit delete-merged --doit --local
– oligofren
Jun 27 '17 at 15:10
You could also use this app to auto delete merged branches.
– Sebass van Boxel
Aug 7 '18 at 16:16
35
35
git branch -D deletes branches that have NOT been merged! Use with care!
– Dan Solovay
Dec 23 '16 at 14:05
git branch -D deletes branches that have NOT been merged! Use with care!
– Dan Solovay
Dec 23 '16 at 14:05
27
27
To be slightly more specific
git branch -D deletes any branch whether it as been merged or not.– PhilT
Feb 8 '17 at 9:48
To be slightly more specific
git branch -D deletes any branch whether it as been merged or not.– PhilT
Feb 8 '17 at 9:48
6
6
You can also do this directly from GitHub, if you go to the 'branches' section of your repo (e.g. github.com/<username>/<repo_name>/branches). There should be a list of all your branches, with a red trashcan icon on the side which will delete the selected branch. Much faster than doing it in the terminal! Will also show how far ahead/behind
master each branch is. However, your local client will still list the old branches if you run git branch -a; use git fetch --prune to remove them (as per this answer ).– user5359531
Feb 24 '17 at 16:13
You can also do this directly from GitHub, if you go to the 'branches' section of your repo (e.g. github.com/<username>/<repo_name>/branches). There should be a list of all your branches, with a red trashcan icon on the side which will delete the selected branch. Much faster than doing it in the terminal! Will also show how far ahead/behind
master each branch is. However, your local client will still list the old branches if you run git branch -a; use git fetch --prune to remove them (as per this answer ).– user5359531
Feb 24 '17 at 16:13
2
2
Script to do this locally or remotely - with safety checks and pre-configured "safe branches": github.com/fatso83/dotfiles/tree/master/utils/…
git delete-merged --doit origin or git delete-merged --doit --local– oligofren
Jun 27 '17 at 15:10
Script to do this locally or remotely - with safety checks and pre-configured "safe branches": github.com/fatso83/dotfiles/tree/master/utils/…
git delete-merged --doit origin or git delete-merged --doit --local– oligofren
Jun 27 '17 at 15:10
You could also use this app to auto delete merged branches.
– Sebass van Boxel
Aug 7 '18 at 16:16
You could also use this app to auto delete merged branches.
– Sebass van Boxel
Aug 7 '18 at 16:16
add a comment |
39 Answers
39
active
oldest
votes
1 2
next
UPDATE:
You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.
First, list all branches that were merged in remote.
git branch --merged
You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.
git branch --merged| egrep -v "(^*|master|dev)"
If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name will not be deleted.
git branch --merged| egrep -v "(^*|master|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | egrep -v "(^*|master|dev)" | xargs git branch -d
You can see that master and dev are excluded in case they are an ancestor.
You can delete a merged local branch with:
git branch -d branchname
If it's not merged, use:
git branch -D branchname
To delete it from the remote in old versions of Git use:
git push origin :branchname
In more recent versions of Git use:
git push --delete origin branchname
Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:
git remote prune origin
or prune individual remote tracking branches, as the other answer suggests, with:
git branch -dr branchname
Hope this helps.
34
WARNING: If you just created a branch it will also delete that one. Make sure to not have a newly created branch in the list before you run the top most command.
– Gary Haran
May 24 '13 at 14:01
118
OPPOSITE OF WARNING: reflog will save your bacon. So don't worry.
– Adam Dymitruk
Aug 20 '14 at 1:05
31
Keep in mind that the first command only deletes local branches, so it isn't as 'dangerous' as some have pointed out.
– ifightcrime
Sep 15 '14 at 23:21
57
PowerShell variant, so that I could find it here next time I googled the answer:git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'develop' -and $_ -notmatch 'master'} | %{git branch -d $_}
– vorou
Dec 20 '15 at 8:12
13
This produces an errorfatal: branch name requiredif you have no branches that should be deleted. To avoid that you can pass-rtoxargsso it won't rungit branch -dif the stdin is empty. (This a GNU xargs extension, according to the man page).
– Marius Gedminas
Feb 9 '16 at 14:40
|
show 26 more comments
To delete all branches on remote that are already merged:
git branch -r --merged | grep -v master | sed 's/origin//:/' | xargs -n 1 git push origin
In more recent versions of Git
git branch -r --merged | grep -v master | sed 's/origin///' | xargs -n 1 git push --delete origin
13
Best answer by far. Just a note, my master branch is nameddevso I had to change that
– Dorian
Feb 13 '14 at 21:33
36
I had to add| grep originaftergrep -v masterto prevent pushing branches of other remotes to origin. Highly recommending testing the output beforehand, usinggit branch -r --merged | grep -v master | grep origin | sed 's/origin//:/' | xargs -n 1 echo
– L0LN1NJ4
Jun 8 '15 at 8:06
8
I slightly modified to excludedevelopbranch as well.git branch -r --merged | grep -v master | grep -v develop | sed 's/origin///' | xargs -n 1 git push --delete origin. Now this turned out to be my alias.
– sarat
Aug 15 '15 at 12:19
6
What made this the best answer I've read, is the-rargument, which I've not seen mentioned anywhere else. It's taken for granted that only local branches are worth doing some housekeeping on. But remotes are full of garbage too.
– Asbjørn Ulsberg
Nov 2 '15 at 17:49
11
Caution - just realized: this will obviously find branches merged to current branch, not master, so if you are onmyFeatureBranchit will wipeorigin/myFeatureBranch. Probably it's best togit checkout masterfirst.
– jakub.g
Feb 5 '16 at 14:40
|
show 6 more comments
Just extending Adam's answer a little bit:
Add this to your Git configuration by running git config -e --global
[alias]
cleanup = "!git branch --merged | grep -v '\*\|master\|develop' | xargs -n 1 git branch -d"
And then you can delete all the local merged branches doing a simple git cleanup.
8
shouldn't the first command be:git branch --merged mastersince you want to look at what has been merged into master, not currently checked out branch?
– Joe Phillips
Aug 12 '16 at 16:23
@JoePhilllips Some people has the main branch not master but insteaddevelopordevand in that case the command will fail withfatal: malformed object nameit's better to have a generic command and you have the responsibility to run it
– smohamed
Aug 13 '16 at 1:14
@SKandeel Yes I agree but most people can figure out to change that for their particular case. It's a little odd to have to be sitting on a certain branch in order for cleanup to work
– Joe Phillips
Aug 15 '16 at 19:39
@JoePhilllips the point of this answer is to package up Adam's answer (the top answer for this question) in helpful git alias. Adam's answer doesn't have what you are suggesting and so many people have found that useful so I would be inclined not to change mine. I would recommend opening the discussion on Adam's answer if you feel strongly about it
– real_ate
Aug 16 '16 at 7:39
9
Adding-rtoxargswill prevent unnecessary errors (branch name required) when running this alias multiple times or when there is no branch left to be deleted. My alias looks like this:cleanup = "!git branch --merged | grep -v -P '^\*|master|develop' | xargs -n1 -r git branch -d"
– spezifanta
Jun 23 '17 at 9:14
|
show 4 more comments
This also works to delete all merged branches except master.
git branch --merged | grep -v '^* master$' | grep -v '^ master$' | xargs git branch -d
3
Now it won't delete any branch withmasterin it. Trygrep -v ^master$for the middle.
– wchargin
Oct 12 '13 at 2:26
I'd also let| grep -v '^*'to avoid deletting current branch if you are not on master
– svassr
Sep 8 '14 at 19:06
4
This is great, thanks! One caveat for anyone using this: note that there are two spaces ingrep -v '^ master$'. If you type it in yourself and miss one, you'll deletemasterif you're not on it.
– styger
Oct 23 '14 at 20:51
3
@Mr.Polywhirl your edit breaks the command and you should revert it. The two spaces are necessary, sincegit branchwill list each branch name on a new line with two spaces to the left if it is not the currently checked out branch. You have essentially guaranteed that anyone who runs this command will delete their master branch unless it is the currently checked out branch.
– styger
Dec 8 '15 at 21:49
add a comment |
You'll want to exclude the master & develop branches from those commands.
Local git clear:
git branch --merged | grep -v '*|master|develop' | xargs -n 1 git branch -d
Remote git clear:
git branch -r --merged | grep -v '*|master|develop' | sed 's/origin///' | xargs -n 1 git push --delete origin
Sync local registry of remote branches:
git fetch -p
3
+1 for the remote version as well (but less needed as we have remote --prune). Also worth noting that thoose won't work with older git version
– malko
Jun 11 '15 at 8:09
3
git config --global --add fetch.prune trueto prune automatically on fetch or pull.
– T3rm1
Dec 18 '15 at 14:51
Mind you, prune is not the same as the remote clear. The remote clear actually deletes the remote branches that are fully merged with your current branch. Prune only cleans up your local registry of remote branches that are already deleted.
– Guido Bouman
Jan 5 '17 at 14:07
The word fully is a bit misleading, as a branch will be considered merged, when it was merged before, but has new commits after the merge, which were not merged.
– scones
Jul 20 '17 at 9:15
To delete all the origin remotes in one call, I used this:git branch -r --merged | grep -v '*|master|develop' | grep '^s*origin/' | sed 's/origin///' | tr "n" " " | xargs git push --delete origin
– GPHemsley
Oct 3 '18 at 13:51
add a comment |
For those of you that are on Windows and prefer PowerShell scripts, here is one that deletes local merged branches:
function Remove-MergedBranches
{
git branch --merged |
ForEach-Object { $_.Trim() } |
Where-Object {$_ -NotMatch "^*"} |
Where-Object {-not ( $_ -Like "*master" )} |
ForEach-Object { git branch -d $_ }
}
11
For curiosity sake, this can be shortened togit branch --merged | ?{-not ($_ -like "*master")} | %{git branch -d $_.trim()}
– Iain Ballard
Oct 8 '14 at 8:27
2
@IainBallard Sure, I could have used aliases. That is not recommended when you want to maximize readability. github.com/darkoperator/PSStyleGuide/blob/master/English.md
– Klas Mellbourn
Oct 8 '14 at 11:36
1
sure. I found your answer very helpful :-) However sometimes the long-form powershell syntax gets in the way of what's going on in the blocks. But primarily, I was putting forward something you might copy/paste or type as a one-off. Thanks again.
– Iain Ballard
Oct 8 '14 at 11:56
@IainBallard You are welcome :)
– Klas Mellbourn
Oct 8 '14 at 14:34
3
Here's a one-liner for Windows cmd shell that preserves master and your current branch:for /f "usebackq" %B in (``git branch --merged^|findstr /v /c:"* " /c:"master"``) do @git branch -d %B(sigh, replace double-backquotes with single, I'm not sure how to format a literal that contains backquotes)
– yoyo
Jan 16 '17 at 23:37
add a comment |
Git Sweep does a great job of this.
add a comment |
Using Git version 2.5.0:
git branch -d `git branch --merged`
11
This can delete themasterbranch btw!
– Islam Wazery
Oct 7 '15 at 13:34
3
True. I only use it when I'm sure I'm onmaster.
– drautb
Oct 7 '15 at 22:24
7
git branch -d $(git branch --merged | grep -v master)
– alexg
Mar 22 '18 at 13:21
add a comment |
You can add the commit to the --merged option.
This way you can make sure only to remove branches which are merged into i.e. the origin/master
Following command will remove merged branches from your origin.
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete
You can test which branches will be removed replacing the git push origin --delete with echo
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo
1
I like the test option
– iwein
Sep 22 '15 at 9:01
add a comment |
I've used Adam's answer for years now. That said, that there are some cases where it wasn't behaving as I expected:
- branches that contained the word "master" were ignored, e.g. "notmaster" or "masterful", rather than only the master branch
- branches that contained the word "dev" were ignored, e.g. "dev-test", rather than only the dev branch
- deleting branches that are reachable from the HEAD of the current branch (that is, not necessarily master)
- in detached HEAD state, deleting every branch reachable from the current commit
1 & 2 were straightforward to address, with just a change to the regex.
3 depends on the context of what you want (i.e. only delete branches that haven't been merged into master or against your current branch).
4 has the potential to be disastrous (although recoverable with git reflog), if you unintentionally ran this in detached HEAD state.
Finally, I wanted this to all be in a one-liner that didn't require a separate (Bash|Ruby|Python) script.
TL;DR
Create a git alias "sweep" that accepts an optional -f flag:
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
and invoke it with:
git sweep
or:
git sweep -f
The long, detailed answer
It was easiest for me to create an example git repo with some branches and commits to test the correct behavior:
Create a new git repo with a single commit
mkdir sweep-test && cd sweep-test && git init
echo "hello" > hello
git add . && git commit -am "initial commit"
Create some new branches
git branch foo && git branch bar && git branch develop && git branch notmaster && git branch masterful
git branch --list
bar
develop
foo
* master
masterful
notmaster
Desired behavior: select all merged branches except: master, develop or current
The original regex misses the branches "masterful" and "notmaster" :
git checkout foo
git branch --merged | egrep -v "(^*|master|dev)"
bar
With the updated regex (which now excludes "develop" rather than "dev"):
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Switch to branch foo, make a new commit, then checkout a new branch, foobar, based on foo:
echo "foo" > foo
git add . && git commit -am "foo"
git checkout -b foobar
echo "foobar" > foobar
git add . && git commit -am "foobar"
My current branch is foobar, and if I re-run the above command to list the branches I want to delete, the branch "foo" is included even though it hasn't been merged into master:
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
masterful
notmaster
However, if I run the same command on master, the branch "foo" is not included:
git checkout master && git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
And this is simply because git branch --merged defaults to the HEAD of the current branch if not otherwise specified. At least for my workflow, I don't want to delete local branches unless they've been merged to master, so I prefer the following variant:
git checkout foobar
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Detached HEAD state
Relying on the default behavior of git branch --merged has even more significant consequences in detached HEAD state:
git checkout foobar
git checkout HEAD~0
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
foobar
masterful
notmaster
This would have deleted the branch I was just on, "foobar" along with "foo", which is almost certainly not the desired outcome.
With our revised command, however:
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
One line, including the actual delete
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)" | xargs git branch -d
All wrapped up into a git alias "sweep":
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
The alias accepts an optional -f flag. The default behavior is to only delete branches that have been merged into master, but the -f flag will delete branches that have been merged into the current branch.
git sweep
Deleted branch bar (was 9a56952).
Deleted branch masterful (was 9a56952).
Deleted branch notmaster (was 9a56952).
git sweep -f
Deleted branch foo (was 2cea1ab).
add a comment |
I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.
#!/usr/bin/env ruby
current_branch = `git symbolic-ref --short HEAD`.chomp
if current_branch != "master"
if $?.exitstatus == 0
puts "WARNING: You are on branch #{current_branch}, NOT master."
else
puts "WARNING: You are not on a branch"
end
puts
end
puts "Fetching merged branches..."
remote_branches= `git branch -r --merged`.
split("n").
map(&:strip).
reject {|b| b =~ //(#{current_branch}|master)/}
local_branches= `git branch --merged`.
gsub(/^* /, '').
split("n").
map(&:strip).
reject {|b| b =~ /(#{current_branch}|master)/}
if remote_branches.empty? && local_branches.empty?
puts "No existing branches have been merged into #{current_branch}."
else
puts "This will remove the following branches:"
puts remote_branches.join("n")
puts local_branches.join("n")
puts "Proceed?"
if gets =~ /^y/i
remote_branches.each do |b|
remote, branch = b.split(///)
`git push #{remote} :#{branch}`
end
# Remove local branches
`git branch -d #{local_branches.join(' ')}`
else
puts "No branches removed."
end
end
Mind if I steal this tidbit for a little git helper library? github.com/yupiq/git-branch-util
– logan
Dec 19 '12 at 22:28
1
Go for it, I wouldn't have put it here if I cared about people reusing the code in some way
– mmrobins
May 20 '13 at 20:56
@mmrobins You have an extra/at the beginning of the reject statement for theremote_branchesline. Is that a typo or does it serve a purpose?
– Jawwad
Jan 27 '16 at 17:46
@mmrobins, oh never mind I see theb.split(///)line now
– Jawwad
Jan 27 '16 at 17:52
If you want to do basically this but via vanilla bash rather than ruby: stackoverflow.com/a/37999948/430128
– Raman
Jun 23 '16 at 19:14
add a comment |
kuboon's answer missed deleting branches which have the word master in the branch name.
The following improves on his answer:
git branch -r --merged | grep -v "origin/master$" | sed 's/s*origin///' | xargs -n 1 git push --delete origin
Of course, it does not delete the "master" branch itself :)
add a comment |
How to delete merged branches in PowerShell console
git branch --merged | %{git branch -d $_.Trim()}
See GitHub for Windows
1
Higher answers are suggesting filtering master or other branches. For those looking to do that in powershell: git branch --merged | findstr /v "master" | %{git branch -d $_.trim()}
– tredzko
Jul 28 '15 at 15:03
@tredzko Good point. FTR the higher answer is stackoverflow.com/questions/6127328/… - you could repost your comment with that linked and I'd then delete this
– Ruben Bartelink
Feb 23 '16 at 11:40
it also tries to delete* master:)
– iesen
Dec 15 '17 at 8:37
add a comment |
There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.
If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)
$ git rev-list master | grep $(git rev-parse myTopicBranch)
You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.
add a comment |
git branch --merged | grep -Ev '^(. master|*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.
Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.
add a comment |
You can use git-del-br tool.
git-del-br -a
You can install it via pip using
pip install git-del-br
P.S: I am the author of the tool. Any suggestions/feedback are welcome.
@stackoverflow.com/users/100297/martijn-pieters : Why was this answer deleted and downvoted?
– tusharmakkar08
Sep 29 '16 at 16:23
Your answer and tool don't work. I spend a couple hours on it. Nothing.
– SpoiledTechie.com
Nov 15 '17 at 18:55
@SpoiledTechie.com: Can you tell me what problem are you facing exactly? I am using it on a regular basis.
– tusharmakkar08
Nov 16 '17 at 9:53
I can share a screenshot if you want to take this offline? spoiledtechie at that google mail thing. :)
– SpoiledTechie.com
Nov 17 '17 at 16:12
add a comment |
Alias version of Adam's updated answer:
[alias]
branch-cleanup = "!git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d #"
Also, see this answer for handy tips on escaping complex aliases.
add a comment |
If you'd like to delete all local branches that are already merged in to the branch that you are currently on, then I've come up with a safe command to do so, based on earlier answers:
git branch --merged | grep -v * | grep -v '^s*master$' | xargs -t -n 1 git branch -d
This command will not affect your current branch or your master branch. It will also tell you what it's doing before it does it, using the -t flag of xargs.
add a comment |
Try the following command:
git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.
To do the same with remote branches (change origin with your remote name), try:
git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
In case you've multiple remotes, add grep origin | before cut to filter only the origin.
If above command fails, try to delete the merged remote-tracking branches first:
git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
Then git fetch the remote again and use the previous git push -vdcommand again.
If you're using it often, consider adding as aliases into your ~/.gitconfig file.
In case you've removed some branches by mistake, use git reflog to find the lost commits.
add a comment |
Based on some of these answers I made my own Bash script to do it too!
It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.
merged_branches(){
local current_branch=$(git rev-parse --abbrev-ref HEAD)
for branch in $(git branch --merged | cut -c3-)
do
echo "Branch $branch is already merged into $current_branch."
echo "Would you like to delete it? [Y]es/[N]o "
read REPLY
if [[ $REPLY =~ ^[Yy] ]]; then
git branch -d $branch
fi
done
}
add a comment |
I use a git-flow esque naming scheme, so this works very safely for me:
git branch --merged | grep -e "^s+(fix|feature)/" | xargs git branch -d
It basically looks for merged commits that start with either string fix/ or feature/.
add a comment |
Below query works for me
for branch in `git branch -r --merged | grep -v '*|master|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin//, "")}1'`;do git push origin --delete $branch; done
and this will filter any given branch in the grep pipe.
Works well over http clone, but not so well for the ssh connection.
add a comment |
Write a script in which Git checks out all the branches that have been merged to master.
Then do git checkout master.
Finally, delete the merged branches.
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git checkout $branchnew
done
git checkout master
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git push origin --delete $branchnew
done
add a comment |
The accepted solution is pretty good, but has the one issue that it also deletes local branches that were not yet merged into a remote.
If you look at the output of you will see something like
$ git branch --merged master -v
api_doc 3a05427 [gone] Start of describing the Java API
bla 52e080a Update wording.
branch-1.0 32f1a72 [maven-release-plugin] prepare release 1.0.1
initial_proposal 6e59fb0 [gone] Original proposal, converted to AsciiDoc.
issue_248 be2ba3c Skip unit-for-type checking. This needs more work. (#254)
master be2ba3c Skip unit-for-type checking. This needs more work. (#254)
Branches bla and issue_248 are local branches that would be deleted silently.
But you can also see the word [gone], which indicate branches that had been pushed to a remote (which is now gone) and thus denote branches can be deleted.
The original answer can thus be changed to (split into multiline for shorter line length)
git branch --merged master -v |
grep "\[gone\]" |
sed -e 's/^..//' -e 's/S* .*//' |
xargs git branch -d
to protect the not yet merged branches.
Also the grepping for master to protect it, is not needed, as this has a remote at origin and does not show up as gone.
add a comment |
To avoid accidentally running the command from any other branch than master I use the following bash script. Otherwise, running git branch --merged | grep -v "*" | xargs -n 1 git branch -d from a branch that has been merged of off master could delete the master branch.
#!/bin/bash
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
if [[ $branch_name == 'master' ]]; then
read -r -p "Are you sure? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
git branch --merged | grep -v "*" | xargs -n 1 git branch -d
fi
else
echo "Refusing to delete branches that are not merged into '$branch_name'. Checkout master first."
fi
add a comment |
As of 2018.07
Add this to [alias] section of your ~/.gitconfig:
sweep = !"f() { git branch --merged | egrep -v "(^\*|master|dev)" || true | xargs git branch -d; }; f"
Now you can just call git sweep to perform that needed cleanup.
For me, calling git sweep only lists the branches that should be cleaned up, but it does not remove them
– Victor Moraes
Jul 5 '18 at 20:26
add a comment |
On Windows with git bash installed egrep -v will not work
git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
where grep -E -v is equivalent of egrep -v
Use -d to remove already merged branches or
-D to remove unmerged branches
egrep -v works for me. I'm using gitbash from the gitextensions installer though
– Joe Phillips
Jul 10 '18 at 16:47
add a comment |
For Windows you can install Cygwin and remove all remote branches using following command:
git branch -r --merged | "C:cygwin64bingrep.exe" -v master | "C:cygwin64binsed.exe" 's/origin///' | "C:cygwin64binxargs.exe" -n 1 git push --delete origin
add a comment |
To delete local branches that have been merged to master branch I'm using the following alias (git config -e --global):
cleanup = "!git branch --merged master | grep -v '^*\|master' | xargs -n 1 git branch -D"
I'm using git branch -D to avoid error: The branch 'some-branch' is not fully merged. messages while my current checkout is different from master branch.
add a comment |
Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):
#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
# git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain
import gitapi
repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('n'):
branch = branch.strip()
if branch.strip(' *') != 'master':
print(repo.git_command('branch', '-d', branch).strip())
https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc
add a comment |
1 2
next
protected by coldspeed Dec 20 '18 at 4:45
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
39 Answers
39
active
oldest
votes
39 Answers
39
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
UPDATE:
You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.
First, list all branches that were merged in remote.
git branch --merged
You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.
git branch --merged| egrep -v "(^*|master|dev)"
If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name will not be deleted.
git branch --merged| egrep -v "(^*|master|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | egrep -v "(^*|master|dev)" | xargs git branch -d
You can see that master and dev are excluded in case they are an ancestor.
You can delete a merged local branch with:
git branch -d branchname
If it's not merged, use:
git branch -D branchname
To delete it from the remote in old versions of Git use:
git push origin :branchname
In more recent versions of Git use:
git push --delete origin branchname
Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:
git remote prune origin
or prune individual remote tracking branches, as the other answer suggests, with:
git branch -dr branchname
Hope this helps.
34
WARNING: If you just created a branch it will also delete that one. Make sure to not have a newly created branch in the list before you run the top most command.
– Gary Haran
May 24 '13 at 14:01
118
OPPOSITE OF WARNING: reflog will save your bacon. So don't worry.
– Adam Dymitruk
Aug 20 '14 at 1:05
31
Keep in mind that the first command only deletes local branches, so it isn't as 'dangerous' as some have pointed out.
– ifightcrime
Sep 15 '14 at 23:21
57
PowerShell variant, so that I could find it here next time I googled the answer:git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'develop' -and $_ -notmatch 'master'} | %{git branch -d $_}
– vorou
Dec 20 '15 at 8:12
13
This produces an errorfatal: branch name requiredif you have no branches that should be deleted. To avoid that you can pass-rtoxargsso it won't rungit branch -dif the stdin is empty. (This a GNU xargs extension, according to the man page).
– Marius Gedminas
Feb 9 '16 at 14:40
|
show 26 more comments
UPDATE:
You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.
First, list all branches that were merged in remote.
git branch --merged
You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.
git branch --merged| egrep -v "(^*|master|dev)"
If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name will not be deleted.
git branch --merged| egrep -v "(^*|master|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | egrep -v "(^*|master|dev)" | xargs git branch -d
You can see that master and dev are excluded in case they are an ancestor.
You can delete a merged local branch with:
git branch -d branchname
If it's not merged, use:
git branch -D branchname
To delete it from the remote in old versions of Git use:
git push origin :branchname
In more recent versions of Git use:
git push --delete origin branchname
Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:
git remote prune origin
or prune individual remote tracking branches, as the other answer suggests, with:
git branch -dr branchname
Hope this helps.
34
WARNING: If you just created a branch it will also delete that one. Make sure to not have a newly created branch in the list before you run the top most command.
– Gary Haran
May 24 '13 at 14:01
118
OPPOSITE OF WARNING: reflog will save your bacon. So don't worry.
– Adam Dymitruk
Aug 20 '14 at 1:05
31
Keep in mind that the first command only deletes local branches, so it isn't as 'dangerous' as some have pointed out.
– ifightcrime
Sep 15 '14 at 23:21
57
PowerShell variant, so that I could find it here next time I googled the answer:git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'develop' -and $_ -notmatch 'master'} | %{git branch -d $_}
– vorou
Dec 20 '15 at 8:12
13
This produces an errorfatal: branch name requiredif you have no branches that should be deleted. To avoid that you can pass-rtoxargsso it won't rungit branch -dif the stdin is empty. (This a GNU xargs extension, according to the man page).
– Marius Gedminas
Feb 9 '16 at 14:40
|
show 26 more comments
UPDATE:
You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.
First, list all branches that were merged in remote.
git branch --merged
You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.
git branch --merged| egrep -v "(^*|master|dev)"
If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name will not be deleted.
git branch --merged| egrep -v "(^*|master|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | egrep -v "(^*|master|dev)" | xargs git branch -d
You can see that master and dev are excluded in case they are an ancestor.
You can delete a merged local branch with:
git branch -d branchname
If it's not merged, use:
git branch -D branchname
To delete it from the remote in old versions of Git use:
git push origin :branchname
In more recent versions of Git use:
git push --delete origin branchname
Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:
git remote prune origin
or prune individual remote tracking branches, as the other answer suggests, with:
git branch -dr branchname
Hope this helps.
UPDATE:
You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.
First, list all branches that were merged in remote.
git branch --merged
You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.
git branch --merged| egrep -v "(^*|master|dev)"
If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name will not be deleted.
git branch --merged| egrep -v "(^*|master|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | egrep -v "(^*|master|dev)" | xargs git branch -d
You can see that master and dev are excluded in case they are an ancestor.
You can delete a merged local branch with:
git branch -d branchname
If it's not merged, use:
git branch -D branchname
To delete it from the remote in old versions of Git use:
git push origin :branchname
In more recent versions of Git use:
git push --delete origin branchname
Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:
git remote prune origin
or prune individual remote tracking branches, as the other answer suggests, with:
git branch -dr branchname
Hope this helps.
edited Feb 8 at 21:07
Ahmed
1,5271023
1,5271023
answered May 25 '11 at 16:40
Adam DymitrukAdam Dymitruk
86.3k12120129
86.3k12120129
34
WARNING: If you just created a branch it will also delete that one. Make sure to not have a newly created branch in the list before you run the top most command.
– Gary Haran
May 24 '13 at 14:01
118
OPPOSITE OF WARNING: reflog will save your bacon. So don't worry.
– Adam Dymitruk
Aug 20 '14 at 1:05
31
Keep in mind that the first command only deletes local branches, so it isn't as 'dangerous' as some have pointed out.
– ifightcrime
Sep 15 '14 at 23:21
57
PowerShell variant, so that I could find it here next time I googled the answer:git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'develop' -and $_ -notmatch 'master'} | %{git branch -d $_}
– vorou
Dec 20 '15 at 8:12
13
This produces an errorfatal: branch name requiredif you have no branches that should be deleted. To avoid that you can pass-rtoxargsso it won't rungit branch -dif the stdin is empty. (This a GNU xargs extension, according to the man page).
– Marius Gedminas
Feb 9 '16 at 14:40
|
show 26 more comments
34
WARNING: If you just created a branch it will also delete that one. Make sure to not have a newly created branch in the list before you run the top most command.
– Gary Haran
May 24 '13 at 14:01
118
OPPOSITE OF WARNING: reflog will save your bacon. So don't worry.
– Adam Dymitruk
Aug 20 '14 at 1:05
31
Keep in mind that the first command only deletes local branches, so it isn't as 'dangerous' as some have pointed out.
– ifightcrime
Sep 15 '14 at 23:21
57
PowerShell variant, so that I could find it here next time I googled the answer:git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'develop' -and $_ -notmatch 'master'} | %{git branch -d $_}
– vorou
Dec 20 '15 at 8:12
13
This produces an errorfatal: branch name requiredif you have no branches that should be deleted. To avoid that you can pass-rtoxargsso it won't rungit branch -dif the stdin is empty. (This a GNU xargs extension, according to the man page).
– Marius Gedminas
Feb 9 '16 at 14:40
34
34
WARNING: If you just created a branch it will also delete that one. Make sure to not have a newly created branch in the list before you run the top most command.
– Gary Haran
May 24 '13 at 14:01
WARNING: If you just created a branch it will also delete that one. Make sure to not have a newly created branch in the list before you run the top most command.
– Gary Haran
May 24 '13 at 14:01
118
118
OPPOSITE OF WARNING: reflog will save your bacon. So don't worry.
– Adam Dymitruk
Aug 20 '14 at 1:05
OPPOSITE OF WARNING: reflog will save your bacon. So don't worry.
– Adam Dymitruk
Aug 20 '14 at 1:05
31
31
Keep in mind that the first command only deletes local branches, so it isn't as 'dangerous' as some have pointed out.
– ifightcrime
Sep 15 '14 at 23:21
Keep in mind that the first command only deletes local branches, so it isn't as 'dangerous' as some have pointed out.
– ifightcrime
Sep 15 '14 at 23:21
57
57
PowerShell variant, so that I could find it here next time I googled the answer:
git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'develop' -and $_ -notmatch 'master'} | %{git branch -d $_}– vorou
Dec 20 '15 at 8:12
PowerShell variant, so that I could find it here next time I googled the answer:
git branch --merged | %{$_.trim()} | ?{$_ -notmatch 'develop' -and $_ -notmatch 'master'} | %{git branch -d $_}– vorou
Dec 20 '15 at 8:12
13
13
This produces an error
fatal: branch name required if you have no branches that should be deleted. To avoid that you can pass -r to xargs so it won't run git branch -d if the stdin is empty. (This a GNU xargs extension, according to the man page).– Marius Gedminas
Feb 9 '16 at 14:40
This produces an error
fatal: branch name required if you have no branches that should be deleted. To avoid that you can pass -r to xargs so it won't run git branch -d if the stdin is empty. (This a GNU xargs extension, according to the man page).– Marius Gedminas
Feb 9 '16 at 14:40
|
show 26 more comments
To delete all branches on remote that are already merged:
git branch -r --merged | grep -v master | sed 's/origin//:/' | xargs -n 1 git push origin
In more recent versions of Git
git branch -r --merged | grep -v master | sed 's/origin///' | xargs -n 1 git push --delete origin
13
Best answer by far. Just a note, my master branch is nameddevso I had to change that
– Dorian
Feb 13 '14 at 21:33
36
I had to add| grep originaftergrep -v masterto prevent pushing branches of other remotes to origin. Highly recommending testing the output beforehand, usinggit branch -r --merged | grep -v master | grep origin | sed 's/origin//:/' | xargs -n 1 echo
– L0LN1NJ4
Jun 8 '15 at 8:06
8
I slightly modified to excludedevelopbranch as well.git branch -r --merged | grep -v master | grep -v develop | sed 's/origin///' | xargs -n 1 git push --delete origin. Now this turned out to be my alias.
– sarat
Aug 15 '15 at 12:19
6
What made this the best answer I've read, is the-rargument, which I've not seen mentioned anywhere else. It's taken for granted that only local branches are worth doing some housekeeping on. But remotes are full of garbage too.
– Asbjørn Ulsberg
Nov 2 '15 at 17:49
11
Caution - just realized: this will obviously find branches merged to current branch, not master, so if you are onmyFeatureBranchit will wipeorigin/myFeatureBranch. Probably it's best togit checkout masterfirst.
– jakub.g
Feb 5 '16 at 14:40
|
show 6 more comments
To delete all branches on remote that are already merged:
git branch -r --merged | grep -v master | sed 's/origin//:/' | xargs -n 1 git push origin
In more recent versions of Git
git branch -r --merged | grep -v master | sed 's/origin///' | xargs -n 1 git push --delete origin
13
Best answer by far. Just a note, my master branch is nameddevso I had to change that
– Dorian
Feb 13 '14 at 21:33
36
I had to add| grep originaftergrep -v masterto prevent pushing branches of other remotes to origin. Highly recommending testing the output beforehand, usinggit branch -r --merged | grep -v master | grep origin | sed 's/origin//:/' | xargs -n 1 echo
– L0LN1NJ4
Jun 8 '15 at 8:06
8
I slightly modified to excludedevelopbranch as well.git branch -r --merged | grep -v master | grep -v develop | sed 's/origin///' | xargs -n 1 git push --delete origin. Now this turned out to be my alias.
– sarat
Aug 15 '15 at 12:19
6
What made this the best answer I've read, is the-rargument, which I've not seen mentioned anywhere else. It's taken for granted that only local branches are worth doing some housekeeping on. But remotes are full of garbage too.
– Asbjørn Ulsberg
Nov 2 '15 at 17:49
11
Caution - just realized: this will obviously find branches merged to current branch, not master, so if you are onmyFeatureBranchit will wipeorigin/myFeatureBranch. Probably it's best togit checkout masterfirst.
– jakub.g
Feb 5 '16 at 14:40
|
show 6 more comments
To delete all branches on remote that are already merged:
git branch -r --merged | grep -v master | sed 's/origin//:/' | xargs -n 1 git push origin
In more recent versions of Git
git branch -r --merged | grep -v master | sed 's/origin///' | xargs -n 1 git push --delete origin
To delete all branches on remote that are already merged:
git branch -r --merged | grep -v master | sed 's/origin//:/' | xargs -n 1 git push origin
In more recent versions of Git
git branch -r --merged | grep -v master | sed 's/origin///' | xargs -n 1 git push --delete origin
answered Aug 9 '13 at 8:45
kuboonkuboon
5,79412423
5,79412423
13
Best answer by far. Just a note, my master branch is nameddevso I had to change that
– Dorian
Feb 13 '14 at 21:33
36
I had to add| grep originaftergrep -v masterto prevent pushing branches of other remotes to origin. Highly recommending testing the output beforehand, usinggit branch -r --merged | grep -v master | grep origin | sed 's/origin//:/' | xargs -n 1 echo
– L0LN1NJ4
Jun 8 '15 at 8:06
8
I slightly modified to excludedevelopbranch as well.git branch -r --merged | grep -v master | grep -v develop | sed 's/origin///' | xargs -n 1 git push --delete origin. Now this turned out to be my alias.
– sarat
Aug 15 '15 at 12:19
6
What made this the best answer I've read, is the-rargument, which I've not seen mentioned anywhere else. It's taken for granted that only local branches are worth doing some housekeeping on. But remotes are full of garbage too.
– Asbjørn Ulsberg
Nov 2 '15 at 17:49
11
Caution - just realized: this will obviously find branches merged to current branch, not master, so if you are onmyFeatureBranchit will wipeorigin/myFeatureBranch. Probably it's best togit checkout masterfirst.
– jakub.g
Feb 5 '16 at 14:40
|
show 6 more comments
13
Best answer by far. Just a note, my master branch is nameddevso I had to change that
– Dorian
Feb 13 '14 at 21:33
36
I had to add| grep originaftergrep -v masterto prevent pushing branches of other remotes to origin. Highly recommending testing the output beforehand, usinggit branch -r --merged | grep -v master | grep origin | sed 's/origin//:/' | xargs -n 1 echo
– L0LN1NJ4
Jun 8 '15 at 8:06
8
I slightly modified to excludedevelopbranch as well.git branch -r --merged | grep -v master | grep -v develop | sed 's/origin///' | xargs -n 1 git push --delete origin. Now this turned out to be my alias.
– sarat
Aug 15 '15 at 12:19
6
What made this the best answer I've read, is the-rargument, which I've not seen mentioned anywhere else. It's taken for granted that only local branches are worth doing some housekeeping on. But remotes are full of garbage too.
– Asbjørn Ulsberg
Nov 2 '15 at 17:49
11
Caution - just realized: this will obviously find branches merged to current branch, not master, so if you are onmyFeatureBranchit will wipeorigin/myFeatureBranch. Probably it's best togit checkout masterfirst.
– jakub.g
Feb 5 '16 at 14:40
13
13
Best answer by far. Just a note, my master branch is named
dev so I had to change that– Dorian
Feb 13 '14 at 21:33
Best answer by far. Just a note, my master branch is named
dev so I had to change that– Dorian
Feb 13 '14 at 21:33
36
36
I had to add
| grep origin after grep -v master to prevent pushing branches of other remotes to origin. Highly recommending testing the output beforehand, using git branch -r --merged | grep -v master | grep origin | sed 's/origin//:/' | xargs -n 1 echo– L0LN1NJ4
Jun 8 '15 at 8:06
I had to add
| grep origin after grep -v master to prevent pushing branches of other remotes to origin. Highly recommending testing the output beforehand, using git branch -r --merged | grep -v master | grep origin | sed 's/origin//:/' | xargs -n 1 echo– L0LN1NJ4
Jun 8 '15 at 8:06
8
8
I slightly modified to exclude
develop branch as well. git branch -r --merged | grep -v master | grep -v develop | sed 's/origin///' | xargs -n 1 git push --delete origin. Now this turned out to be my alias.– sarat
Aug 15 '15 at 12:19
I slightly modified to exclude
develop branch as well. git branch -r --merged | grep -v master | grep -v develop | sed 's/origin///' | xargs -n 1 git push --delete origin. Now this turned out to be my alias.– sarat
Aug 15 '15 at 12:19
6
6
What made this the best answer I've read, is the
-r argument, which I've not seen mentioned anywhere else. It's taken for granted that only local branches are worth doing some housekeeping on. But remotes are full of garbage too.– Asbjørn Ulsberg
Nov 2 '15 at 17:49
What made this the best answer I've read, is the
-r argument, which I've not seen mentioned anywhere else. It's taken for granted that only local branches are worth doing some housekeeping on. But remotes are full of garbage too.– Asbjørn Ulsberg
Nov 2 '15 at 17:49
11
11
Caution - just realized: this will obviously find branches merged to current branch, not master, so if you are on
myFeatureBranch it will wipe origin/myFeatureBranch. Probably it's best to git checkout master first.– jakub.g
Feb 5 '16 at 14:40
Caution - just realized: this will obviously find branches merged to current branch, not master, so if you are on
myFeatureBranch it will wipe origin/myFeatureBranch. Probably it's best to git checkout master first.– jakub.g
Feb 5 '16 at 14:40
|
show 6 more comments
Just extending Adam's answer a little bit:
Add this to your Git configuration by running git config -e --global
[alias]
cleanup = "!git branch --merged | grep -v '\*\|master\|develop' | xargs -n 1 git branch -d"
And then you can delete all the local merged branches doing a simple git cleanup.
8
shouldn't the first command be:git branch --merged mastersince you want to look at what has been merged into master, not currently checked out branch?
– Joe Phillips
Aug 12 '16 at 16:23
@JoePhilllips Some people has the main branch not master but insteaddevelopordevand in that case the command will fail withfatal: malformed object nameit's better to have a generic command and you have the responsibility to run it
– smohamed
Aug 13 '16 at 1:14
@SKandeel Yes I agree but most people can figure out to change that for their particular case. It's a little odd to have to be sitting on a certain branch in order for cleanup to work
– Joe Phillips
Aug 15 '16 at 19:39
@JoePhilllips the point of this answer is to package up Adam's answer (the top answer for this question) in helpful git alias. Adam's answer doesn't have what you are suggesting and so many people have found that useful so I would be inclined not to change mine. I would recommend opening the discussion on Adam's answer if you feel strongly about it
– real_ate
Aug 16 '16 at 7:39
9
Adding-rtoxargswill prevent unnecessary errors (branch name required) when running this alias multiple times or when there is no branch left to be deleted. My alias looks like this:cleanup = "!git branch --merged | grep -v -P '^\*|master|develop' | xargs -n1 -r git branch -d"
– spezifanta
Jun 23 '17 at 9:14
|
show 4 more comments
Just extending Adam's answer a little bit:
Add this to your Git configuration by running git config -e --global
[alias]
cleanup = "!git branch --merged | grep -v '\*\|master\|develop' | xargs -n 1 git branch -d"
And then you can delete all the local merged branches doing a simple git cleanup.
8
shouldn't the first command be:git branch --merged mastersince you want to look at what has been merged into master, not currently checked out branch?
– Joe Phillips
Aug 12 '16 at 16:23
@JoePhilllips Some people has the main branch not master but insteaddevelopordevand in that case the command will fail withfatal: malformed object nameit's better to have a generic command and you have the responsibility to run it
– smohamed
Aug 13 '16 at 1:14
@SKandeel Yes I agree but most people can figure out to change that for their particular case. It's a little odd to have to be sitting on a certain branch in order for cleanup to work
– Joe Phillips
Aug 15 '16 at 19:39
@JoePhilllips the point of this answer is to package up Adam's answer (the top answer for this question) in helpful git alias. Adam's answer doesn't have what you are suggesting and so many people have found that useful so I would be inclined not to change mine. I would recommend opening the discussion on Adam's answer if you feel strongly about it
– real_ate
Aug 16 '16 at 7:39
9
Adding-rtoxargswill prevent unnecessary errors (branch name required) when running this alias multiple times or when there is no branch left to be deleted. My alias looks like this:cleanup = "!git branch --merged | grep -v -P '^\*|master|develop' | xargs -n1 -r git branch -d"
– spezifanta
Jun 23 '17 at 9:14
|
show 4 more comments
Just extending Adam's answer a little bit:
Add this to your Git configuration by running git config -e --global
[alias]
cleanup = "!git branch --merged | grep -v '\*\|master\|develop' | xargs -n 1 git branch -d"
And then you can delete all the local merged branches doing a simple git cleanup.
Just extending Adam's answer a little bit:
Add this to your Git configuration by running git config -e --global
[alias]
cleanup = "!git branch --merged | grep -v '\*\|master\|develop' | xargs -n 1 git branch -d"
And then you can delete all the local merged branches doing a simple git cleanup.
edited Mar 29 '18 at 8:08
answered Feb 18 '14 at 15:08
real_atereal_ate
5,72332139
5,72332139
8
shouldn't the first command be:git branch --merged mastersince you want to look at what has been merged into master, not currently checked out branch?
– Joe Phillips
Aug 12 '16 at 16:23
@JoePhilllips Some people has the main branch not master but insteaddevelopordevand in that case the command will fail withfatal: malformed object nameit's better to have a generic command and you have the responsibility to run it
– smohamed
Aug 13 '16 at 1:14
@SKandeel Yes I agree but most people can figure out to change that for their particular case. It's a little odd to have to be sitting on a certain branch in order for cleanup to work
– Joe Phillips
Aug 15 '16 at 19:39
@JoePhilllips the point of this answer is to package up Adam's answer (the top answer for this question) in helpful git alias. Adam's answer doesn't have what you are suggesting and so many people have found that useful so I would be inclined not to change mine. I would recommend opening the discussion on Adam's answer if you feel strongly about it
– real_ate
Aug 16 '16 at 7:39
9
Adding-rtoxargswill prevent unnecessary errors (branch name required) when running this alias multiple times or when there is no branch left to be deleted. My alias looks like this:cleanup = "!git branch --merged | grep -v -P '^\*|master|develop' | xargs -n1 -r git branch -d"
– spezifanta
Jun 23 '17 at 9:14
|
show 4 more comments
8
shouldn't the first command be:git branch --merged mastersince you want to look at what has been merged into master, not currently checked out branch?
– Joe Phillips
Aug 12 '16 at 16:23
@JoePhilllips Some people has the main branch not master but insteaddevelopordevand in that case the command will fail withfatal: malformed object nameit's better to have a generic command and you have the responsibility to run it
– smohamed
Aug 13 '16 at 1:14
@SKandeel Yes I agree but most people can figure out to change that for their particular case. It's a little odd to have to be sitting on a certain branch in order for cleanup to work
– Joe Phillips
Aug 15 '16 at 19:39
@JoePhilllips the point of this answer is to package up Adam's answer (the top answer for this question) in helpful git alias. Adam's answer doesn't have what you are suggesting and so many people have found that useful so I would be inclined not to change mine. I would recommend opening the discussion on Adam's answer if you feel strongly about it
– real_ate
Aug 16 '16 at 7:39
9
Adding-rtoxargswill prevent unnecessary errors (branch name required) when running this alias multiple times or when there is no branch left to be deleted. My alias looks like this:cleanup = "!git branch --merged | grep -v -P '^\*|master|develop' | xargs -n1 -r git branch -d"
– spezifanta
Jun 23 '17 at 9:14
8
8
shouldn't the first command be:
git branch --merged master since you want to look at what has been merged into master, not currently checked out branch?– Joe Phillips
Aug 12 '16 at 16:23
shouldn't the first command be:
git branch --merged master since you want to look at what has been merged into master, not currently checked out branch?– Joe Phillips
Aug 12 '16 at 16:23
@JoePhilllips Some people has the main branch not master but instead
develop or dev and in that case the command will fail with fatal: malformed object name it's better to have a generic command and you have the responsibility to run it– smohamed
Aug 13 '16 at 1:14
@JoePhilllips Some people has the main branch not master but instead
develop or dev and in that case the command will fail with fatal: malformed object name it's better to have a generic command and you have the responsibility to run it– smohamed
Aug 13 '16 at 1:14
@SKandeel Yes I agree but most people can figure out to change that for their particular case. It's a little odd to have to be sitting on a certain branch in order for cleanup to work
– Joe Phillips
Aug 15 '16 at 19:39
@SKandeel Yes I agree but most people can figure out to change that for their particular case. It's a little odd to have to be sitting on a certain branch in order for cleanup to work
– Joe Phillips
Aug 15 '16 at 19:39
@JoePhilllips the point of this answer is to package up Adam's answer (the top answer for this question) in helpful git alias. Adam's answer doesn't have what you are suggesting and so many people have found that useful so I would be inclined not to change mine. I would recommend opening the discussion on Adam's answer if you feel strongly about it
– real_ate
Aug 16 '16 at 7:39
@JoePhilllips the point of this answer is to package up Adam's answer (the top answer for this question) in helpful git alias. Adam's answer doesn't have what you are suggesting and so many people have found that useful so I would be inclined not to change mine. I would recommend opening the discussion on Adam's answer if you feel strongly about it
– real_ate
Aug 16 '16 at 7:39
9
9
Adding
-r to xargs will prevent unnecessary errors (branch name required) when running this alias multiple times or when there is no branch left to be deleted. My alias looks like this: cleanup = "!git branch --merged | grep -v -P '^\*|master|develop' | xargs -n1 -r git branch -d"– spezifanta
Jun 23 '17 at 9:14
Adding
-r to xargs will prevent unnecessary errors (branch name required) when running this alias multiple times or when there is no branch left to be deleted. My alias looks like this: cleanup = "!git branch --merged | grep -v -P '^\*|master|develop' | xargs -n1 -r git branch -d"– spezifanta
Jun 23 '17 at 9:14
|
show 4 more comments
This also works to delete all merged branches except master.
git branch --merged | grep -v '^* master$' | grep -v '^ master$' | xargs git branch -d
3
Now it won't delete any branch withmasterin it. Trygrep -v ^master$for the middle.
– wchargin
Oct 12 '13 at 2:26
I'd also let| grep -v '^*'to avoid deletting current branch if you are not on master
– svassr
Sep 8 '14 at 19:06
4
This is great, thanks! One caveat for anyone using this: note that there are two spaces ingrep -v '^ master$'. If you type it in yourself and miss one, you'll deletemasterif you're not on it.
– styger
Oct 23 '14 at 20:51
3
@Mr.Polywhirl your edit breaks the command and you should revert it. The two spaces are necessary, sincegit branchwill list each branch name on a new line with two spaces to the left if it is not the currently checked out branch. You have essentially guaranteed that anyone who runs this command will delete their master branch unless it is the currently checked out branch.
– styger
Dec 8 '15 at 21:49
add a comment |
This also works to delete all merged branches except master.
git branch --merged | grep -v '^* master$' | grep -v '^ master$' | xargs git branch -d
3
Now it won't delete any branch withmasterin it. Trygrep -v ^master$for the middle.
– wchargin
Oct 12 '13 at 2:26
I'd also let| grep -v '^*'to avoid deletting current branch if you are not on master
– svassr
Sep 8 '14 at 19:06
4
This is great, thanks! One caveat for anyone using this: note that there are two spaces ingrep -v '^ master$'. If you type it in yourself and miss one, you'll deletemasterif you're not on it.
– styger
Oct 23 '14 at 20:51
3
@Mr.Polywhirl your edit breaks the command and you should revert it. The two spaces are necessary, sincegit branchwill list each branch name on a new line with two spaces to the left if it is not the currently checked out branch. You have essentially guaranteed that anyone who runs this command will delete their master branch unless it is the currently checked out branch.
– styger
Dec 8 '15 at 21:49
add a comment |
This also works to delete all merged branches except master.
git branch --merged | grep -v '^* master$' | grep -v '^ master$' | xargs git branch -d
This also works to delete all merged branches except master.
git branch --merged | grep -v '^* master$' | grep -v '^ master$' | xargs git branch -d
edited May 18 '16 at 20:21
mkobit
21.3k690103
21.3k690103
answered Feb 7 '13 at 1:06
Ismael AbreuIsmael Abreu
14.4k25066
14.4k25066
3
Now it won't delete any branch withmasterin it. Trygrep -v ^master$for the middle.
– wchargin
Oct 12 '13 at 2:26
I'd also let| grep -v '^*'to avoid deletting current branch if you are not on master
– svassr
Sep 8 '14 at 19:06
4
This is great, thanks! One caveat for anyone using this: note that there are two spaces ingrep -v '^ master$'. If you type it in yourself and miss one, you'll deletemasterif you're not on it.
– styger
Oct 23 '14 at 20:51
3
@Mr.Polywhirl your edit breaks the command and you should revert it. The two spaces are necessary, sincegit branchwill list each branch name on a new line with two spaces to the left if it is not the currently checked out branch. You have essentially guaranteed that anyone who runs this command will delete their master branch unless it is the currently checked out branch.
– styger
Dec 8 '15 at 21:49
add a comment |
3
Now it won't delete any branch withmasterin it. Trygrep -v ^master$for the middle.
– wchargin
Oct 12 '13 at 2:26
I'd also let| grep -v '^*'to avoid deletting current branch if you are not on master
– svassr
Sep 8 '14 at 19:06
4
This is great, thanks! One caveat for anyone using this: note that there are two spaces ingrep -v '^ master$'. If you type it in yourself and miss one, you'll deletemasterif you're not on it.
– styger
Oct 23 '14 at 20:51
3
@Mr.Polywhirl your edit breaks the command and you should revert it. The two spaces are necessary, sincegit branchwill list each branch name on a new line with two spaces to the left if it is not the currently checked out branch. You have essentially guaranteed that anyone who runs this command will delete their master branch unless it is the currently checked out branch.
– styger
Dec 8 '15 at 21:49
3
3
Now it won't delete any branch with
master in it. Try grep -v ^master$ for the middle.– wchargin
Oct 12 '13 at 2:26
Now it won't delete any branch with
master in it. Try grep -v ^master$ for the middle.– wchargin
Oct 12 '13 at 2:26
I'd also let
| grep -v '^*' to avoid deletting current branch if you are not on master– svassr
Sep 8 '14 at 19:06
I'd also let
| grep -v '^*' to avoid deletting current branch if you are not on master– svassr
Sep 8 '14 at 19:06
4
4
This is great, thanks! One caveat for anyone using this: note that there are two spaces in
grep -v '^ master$'. If you type it in yourself and miss one, you'll delete master if you're not on it.– styger
Oct 23 '14 at 20:51
This is great, thanks! One caveat for anyone using this: note that there are two spaces in
grep -v '^ master$'. If you type it in yourself and miss one, you'll delete master if you're not on it.– styger
Oct 23 '14 at 20:51
3
3
@Mr.Polywhirl your edit breaks the command and you should revert it. The two spaces are necessary, since
git branch will list each branch name on a new line with two spaces to the left if it is not the currently checked out branch. You have essentially guaranteed that anyone who runs this command will delete their master branch unless it is the currently checked out branch.– styger
Dec 8 '15 at 21:49
@Mr.Polywhirl your edit breaks the command and you should revert it. The two spaces are necessary, since
git branch will list each branch name on a new line with two spaces to the left if it is not the currently checked out branch. You have essentially guaranteed that anyone who runs this command will delete their master branch unless it is the currently checked out branch.– styger
Dec 8 '15 at 21:49
add a comment |
You'll want to exclude the master & develop branches from those commands.
Local git clear:
git branch --merged | grep -v '*|master|develop' | xargs -n 1 git branch -d
Remote git clear:
git branch -r --merged | grep -v '*|master|develop' | sed 's/origin///' | xargs -n 1 git push --delete origin
Sync local registry of remote branches:
git fetch -p
3
+1 for the remote version as well (but less needed as we have remote --prune). Also worth noting that thoose won't work with older git version
– malko
Jun 11 '15 at 8:09
3
git config --global --add fetch.prune trueto prune automatically on fetch or pull.
– T3rm1
Dec 18 '15 at 14:51
Mind you, prune is not the same as the remote clear. The remote clear actually deletes the remote branches that are fully merged with your current branch. Prune only cleans up your local registry of remote branches that are already deleted.
– Guido Bouman
Jan 5 '17 at 14:07
The word fully is a bit misleading, as a branch will be considered merged, when it was merged before, but has new commits after the merge, which were not merged.
– scones
Jul 20 '17 at 9:15
To delete all the origin remotes in one call, I used this:git branch -r --merged | grep -v '*|master|develop' | grep '^s*origin/' | sed 's/origin///' | tr "n" " " | xargs git push --delete origin
– GPHemsley
Oct 3 '18 at 13:51
add a comment |
You'll want to exclude the master & develop branches from those commands.
Local git clear:
git branch --merged | grep -v '*|master|develop' | xargs -n 1 git branch -d
Remote git clear:
git branch -r --merged | grep -v '*|master|develop' | sed 's/origin///' | xargs -n 1 git push --delete origin
Sync local registry of remote branches:
git fetch -p
3
+1 for the remote version as well (but less needed as we have remote --prune). Also worth noting that thoose won't work with older git version
– malko
Jun 11 '15 at 8:09
3
git config --global --add fetch.prune trueto prune automatically on fetch or pull.
– T3rm1
Dec 18 '15 at 14:51
Mind you, prune is not the same as the remote clear. The remote clear actually deletes the remote branches that are fully merged with your current branch. Prune only cleans up your local registry of remote branches that are already deleted.
– Guido Bouman
Jan 5 '17 at 14:07
The word fully is a bit misleading, as a branch will be considered merged, when it was merged before, but has new commits after the merge, which were not merged.
– scones
Jul 20 '17 at 9:15
To delete all the origin remotes in one call, I used this:git branch -r --merged | grep -v '*|master|develop' | grep '^s*origin/' | sed 's/origin///' | tr "n" " " | xargs git push --delete origin
– GPHemsley
Oct 3 '18 at 13:51
add a comment |
You'll want to exclude the master & develop branches from those commands.
Local git clear:
git branch --merged | grep -v '*|master|develop' | xargs -n 1 git branch -d
Remote git clear:
git branch -r --merged | grep -v '*|master|develop' | sed 's/origin///' | xargs -n 1 git push --delete origin
Sync local registry of remote branches:
git fetch -p
You'll want to exclude the master & develop branches from those commands.
Local git clear:
git branch --merged | grep -v '*|master|develop' | xargs -n 1 git branch -d
Remote git clear:
git branch -r --merged | grep -v '*|master|develop' | sed 's/origin///' | xargs -n 1 git push --delete origin
Sync local registry of remote branches:
git fetch -p
edited Dec 20 '15 at 4:48
New Alexandria
5,29734059
5,29734059
answered Jul 3 '14 at 16:18
Guido BoumanGuido Bouman
1,56731529
1,56731529
3
+1 for the remote version as well (but less needed as we have remote --prune). Also worth noting that thoose won't work with older git version
– malko
Jun 11 '15 at 8:09
3
git config --global --add fetch.prune trueto prune automatically on fetch or pull.
– T3rm1
Dec 18 '15 at 14:51
Mind you, prune is not the same as the remote clear. The remote clear actually deletes the remote branches that are fully merged with your current branch. Prune only cleans up your local registry of remote branches that are already deleted.
– Guido Bouman
Jan 5 '17 at 14:07
The word fully is a bit misleading, as a branch will be considered merged, when it was merged before, but has new commits after the merge, which were not merged.
– scones
Jul 20 '17 at 9:15
To delete all the origin remotes in one call, I used this:git branch -r --merged | grep -v '*|master|develop' | grep '^s*origin/' | sed 's/origin///' | tr "n" " " | xargs git push --delete origin
– GPHemsley
Oct 3 '18 at 13:51
add a comment |
3
+1 for the remote version as well (but less needed as we have remote --prune). Also worth noting that thoose won't work with older git version
– malko
Jun 11 '15 at 8:09
3
git config --global --add fetch.prune trueto prune automatically on fetch or pull.
– T3rm1
Dec 18 '15 at 14:51
Mind you, prune is not the same as the remote clear. The remote clear actually deletes the remote branches that are fully merged with your current branch. Prune only cleans up your local registry of remote branches that are already deleted.
– Guido Bouman
Jan 5 '17 at 14:07
The word fully is a bit misleading, as a branch will be considered merged, when it was merged before, but has new commits after the merge, which were not merged.
– scones
Jul 20 '17 at 9:15
To delete all the origin remotes in one call, I used this:git branch -r --merged | grep -v '*|master|develop' | grep '^s*origin/' | sed 's/origin///' | tr "n" " " | xargs git push --delete origin
– GPHemsley
Oct 3 '18 at 13:51
3
3
+1 for the remote version as well (but less needed as we have remote --prune). Also worth noting that thoose won't work with older git version
– malko
Jun 11 '15 at 8:09
+1 for the remote version as well (but less needed as we have remote --prune). Also worth noting that thoose won't work with older git version
– malko
Jun 11 '15 at 8:09
3
3
git config --global --add fetch.prune true to prune automatically on fetch or pull.– T3rm1
Dec 18 '15 at 14:51
git config --global --add fetch.prune true to prune automatically on fetch or pull.– T3rm1
Dec 18 '15 at 14:51
Mind you, prune is not the same as the remote clear. The remote clear actually deletes the remote branches that are fully merged with your current branch. Prune only cleans up your local registry of remote branches that are already deleted.
– Guido Bouman
Jan 5 '17 at 14:07
Mind you, prune is not the same as the remote clear. The remote clear actually deletes the remote branches that are fully merged with your current branch. Prune only cleans up your local registry of remote branches that are already deleted.
– Guido Bouman
Jan 5 '17 at 14:07
The word fully is a bit misleading, as a branch will be considered merged, when it was merged before, but has new commits after the merge, which were not merged.
– scones
Jul 20 '17 at 9:15
The word fully is a bit misleading, as a branch will be considered merged, when it was merged before, but has new commits after the merge, which were not merged.
– scones
Jul 20 '17 at 9:15
To delete all the origin remotes in one call, I used this:
git branch -r --merged | grep -v '*|master|develop' | grep '^s*origin/' | sed 's/origin///' | tr "n" " " | xargs git push --delete origin– GPHemsley
Oct 3 '18 at 13:51
To delete all the origin remotes in one call, I used this:
git branch -r --merged | grep -v '*|master|develop' | grep '^s*origin/' | sed 's/origin///' | tr "n" " " | xargs git push --delete origin– GPHemsley
Oct 3 '18 at 13:51
add a comment |
For those of you that are on Windows and prefer PowerShell scripts, here is one that deletes local merged branches:
function Remove-MergedBranches
{
git branch --merged |
ForEach-Object { $_.Trim() } |
Where-Object {$_ -NotMatch "^*"} |
Where-Object {-not ( $_ -Like "*master" )} |
ForEach-Object { git branch -d $_ }
}
11
For curiosity sake, this can be shortened togit branch --merged | ?{-not ($_ -like "*master")} | %{git branch -d $_.trim()}
– Iain Ballard
Oct 8 '14 at 8:27
2
@IainBallard Sure, I could have used aliases. That is not recommended when you want to maximize readability. github.com/darkoperator/PSStyleGuide/blob/master/English.md
– Klas Mellbourn
Oct 8 '14 at 11:36
1
sure. I found your answer very helpful :-) However sometimes the long-form powershell syntax gets in the way of what's going on in the blocks. But primarily, I was putting forward something you might copy/paste or type as a one-off. Thanks again.
– Iain Ballard
Oct 8 '14 at 11:56
@IainBallard You are welcome :)
– Klas Mellbourn
Oct 8 '14 at 14:34
3
Here's a one-liner for Windows cmd shell that preserves master and your current branch:for /f "usebackq" %B in (``git branch --merged^|findstr /v /c:"* " /c:"master"``) do @git branch -d %B(sigh, replace double-backquotes with single, I'm not sure how to format a literal that contains backquotes)
– yoyo
Jan 16 '17 at 23:37
add a comment |
For those of you that are on Windows and prefer PowerShell scripts, here is one that deletes local merged branches:
function Remove-MergedBranches
{
git branch --merged |
ForEach-Object { $_.Trim() } |
Where-Object {$_ -NotMatch "^*"} |
Where-Object {-not ( $_ -Like "*master" )} |
ForEach-Object { git branch -d $_ }
}
11
For curiosity sake, this can be shortened togit branch --merged | ?{-not ($_ -like "*master")} | %{git branch -d $_.trim()}
– Iain Ballard
Oct 8 '14 at 8:27
2
@IainBallard Sure, I could have used aliases. That is not recommended when you want to maximize readability. github.com/darkoperator/PSStyleGuide/blob/master/English.md
– Klas Mellbourn
Oct 8 '14 at 11:36
1
sure. I found your answer very helpful :-) However sometimes the long-form powershell syntax gets in the way of what's going on in the blocks. But primarily, I was putting forward something you might copy/paste or type as a one-off. Thanks again.
– Iain Ballard
Oct 8 '14 at 11:56
@IainBallard You are welcome :)
– Klas Mellbourn
Oct 8 '14 at 14:34
3
Here's a one-liner for Windows cmd shell that preserves master and your current branch:for /f "usebackq" %B in (``git branch --merged^|findstr /v /c:"* " /c:"master"``) do @git branch -d %B(sigh, replace double-backquotes with single, I'm not sure how to format a literal that contains backquotes)
– yoyo
Jan 16 '17 at 23:37
add a comment |
For those of you that are on Windows and prefer PowerShell scripts, here is one that deletes local merged branches:
function Remove-MergedBranches
{
git branch --merged |
ForEach-Object { $_.Trim() } |
Where-Object {$_ -NotMatch "^*"} |
Where-Object {-not ( $_ -Like "*master" )} |
ForEach-Object { git branch -d $_ }
}
For those of you that are on Windows and prefer PowerShell scripts, here is one that deletes local merged branches:
function Remove-MergedBranches
{
git branch --merged |
ForEach-Object { $_.Trim() } |
Where-Object {$_ -NotMatch "^*"} |
Where-Object {-not ( $_ -Like "*master" )} |
ForEach-Object { git branch -d $_ }
}
edited Sep 7 '15 at 17:41
neverendingqs
1,41411235
1,41411235
answered Jun 10 '14 at 14:00
Klas MellbournKlas Mellbourn
25.3k1399124
25.3k1399124
11
For curiosity sake, this can be shortened togit branch --merged | ?{-not ($_ -like "*master")} | %{git branch -d $_.trim()}
– Iain Ballard
Oct 8 '14 at 8:27
2
@IainBallard Sure, I could have used aliases. That is not recommended when you want to maximize readability. github.com/darkoperator/PSStyleGuide/blob/master/English.md
– Klas Mellbourn
Oct 8 '14 at 11:36
1
sure. I found your answer very helpful :-) However sometimes the long-form powershell syntax gets in the way of what's going on in the blocks. But primarily, I was putting forward something you might copy/paste or type as a one-off. Thanks again.
– Iain Ballard
Oct 8 '14 at 11:56
@IainBallard You are welcome :)
– Klas Mellbourn
Oct 8 '14 at 14:34
3
Here's a one-liner for Windows cmd shell that preserves master and your current branch:for /f "usebackq" %B in (``git branch --merged^|findstr /v /c:"* " /c:"master"``) do @git branch -d %B(sigh, replace double-backquotes with single, I'm not sure how to format a literal that contains backquotes)
– yoyo
Jan 16 '17 at 23:37
add a comment |
11
For curiosity sake, this can be shortened togit branch --merged | ?{-not ($_ -like "*master")} | %{git branch -d $_.trim()}
– Iain Ballard
Oct 8 '14 at 8:27
2
@IainBallard Sure, I could have used aliases. That is not recommended when you want to maximize readability. github.com/darkoperator/PSStyleGuide/blob/master/English.md
– Klas Mellbourn
Oct 8 '14 at 11:36
1
sure. I found your answer very helpful :-) However sometimes the long-form powershell syntax gets in the way of what's going on in the blocks. But primarily, I was putting forward something you might copy/paste or type as a one-off. Thanks again.
– Iain Ballard
Oct 8 '14 at 11:56
@IainBallard You are welcome :)
– Klas Mellbourn
Oct 8 '14 at 14:34
3
Here's a one-liner for Windows cmd shell that preserves master and your current branch:for /f "usebackq" %B in (``git branch --merged^|findstr /v /c:"* " /c:"master"``) do @git branch -d %B(sigh, replace double-backquotes with single, I'm not sure how to format a literal that contains backquotes)
– yoyo
Jan 16 '17 at 23:37
11
11
For curiosity sake, this can be shortened to
git branch --merged | ?{-not ($_ -like "*master")} | %{git branch -d $_.trim()}– Iain Ballard
Oct 8 '14 at 8:27
For curiosity sake, this can be shortened to
git branch --merged | ?{-not ($_ -like "*master")} | %{git branch -d $_.trim()}– Iain Ballard
Oct 8 '14 at 8:27
2
2
@IainBallard Sure, I could have used aliases. That is not recommended when you want to maximize readability. github.com/darkoperator/PSStyleGuide/blob/master/English.md
– Klas Mellbourn
Oct 8 '14 at 11:36
@IainBallard Sure, I could have used aliases. That is not recommended when you want to maximize readability. github.com/darkoperator/PSStyleGuide/blob/master/English.md
– Klas Mellbourn
Oct 8 '14 at 11:36
1
1
sure. I found your answer very helpful :-) However sometimes the long-form powershell syntax gets in the way of what's going on in the blocks. But primarily, I was putting forward something you might copy/paste or type as a one-off. Thanks again.
– Iain Ballard
Oct 8 '14 at 11:56
sure. I found your answer very helpful :-) However sometimes the long-form powershell syntax gets in the way of what's going on in the blocks. But primarily, I was putting forward something you might copy/paste or type as a one-off. Thanks again.
– Iain Ballard
Oct 8 '14 at 11:56
@IainBallard You are welcome :)
– Klas Mellbourn
Oct 8 '14 at 14:34
@IainBallard You are welcome :)
– Klas Mellbourn
Oct 8 '14 at 14:34
3
3
Here's a one-liner for Windows cmd shell that preserves master and your current branch:
for /f "usebackq" %B in (``git branch --merged^|findstr /v /c:"* " /c:"master"``) do @git branch -d %B (sigh, replace double-backquotes with single, I'm not sure how to format a literal that contains backquotes)– yoyo
Jan 16 '17 at 23:37
Here's a one-liner for Windows cmd shell that preserves master and your current branch:
for /f "usebackq" %B in (``git branch --merged^|findstr /v /c:"* " /c:"master"``) do @git branch -d %B (sigh, replace double-backquotes with single, I'm not sure how to format a literal that contains backquotes)– yoyo
Jan 16 '17 at 23:37
add a comment |
Git Sweep does a great job of this.
add a comment |
Git Sweep does a great job of this.
add a comment |
Git Sweep does a great job of this.
Git Sweep does a great job of this.
edited Aug 31 '17 at 23:54
Peter Mortensen
13.7k1986112
13.7k1986112
answered Feb 4 '13 at 13:53
paulpaul
25924
25924
add a comment |
add a comment |
Using Git version 2.5.0:
git branch -d `git branch --merged`
11
This can delete themasterbranch btw!
– Islam Wazery
Oct 7 '15 at 13:34
3
True. I only use it when I'm sure I'm onmaster.
– drautb
Oct 7 '15 at 22:24
7
git branch -d $(git branch --merged | grep -v master)
– alexg
Mar 22 '18 at 13:21
add a comment |
Using Git version 2.5.0:
git branch -d `git branch --merged`
11
This can delete themasterbranch btw!
– Islam Wazery
Oct 7 '15 at 13:34
3
True. I only use it when I'm sure I'm onmaster.
– drautb
Oct 7 '15 at 22:24
7
git branch -d $(git branch --merged | grep -v master)
– alexg
Mar 22 '18 at 13:21
add a comment |
Using Git version 2.5.0:
git branch -d `git branch --merged`
Using Git version 2.5.0:
git branch -d `git branch --merged`
edited Aug 31 '17 at 23:59
Peter Mortensen
13.7k1986112
13.7k1986112
answered Sep 14 '15 at 16:20
drautbdrautb
312312
312312
11
This can delete themasterbranch btw!
– Islam Wazery
Oct 7 '15 at 13:34
3
True. I only use it when I'm sure I'm onmaster.
– drautb
Oct 7 '15 at 22:24
7
git branch -d $(git branch --merged | grep -v master)
– alexg
Mar 22 '18 at 13:21
add a comment |
11
This can delete themasterbranch btw!
– Islam Wazery
Oct 7 '15 at 13:34
3
True. I only use it when I'm sure I'm onmaster.
– drautb
Oct 7 '15 at 22:24
7
git branch -d $(git branch --merged | grep -v master)
– alexg
Mar 22 '18 at 13:21
11
11
This can delete the
master branch btw!– Islam Wazery
Oct 7 '15 at 13:34
This can delete the
master branch btw!– Islam Wazery
Oct 7 '15 at 13:34
3
3
True. I only use it when I'm sure I'm on
master.– drautb
Oct 7 '15 at 22:24
True. I only use it when I'm sure I'm on
master.– drautb
Oct 7 '15 at 22:24
7
7
git branch -d $(git branch --merged | grep -v master)– alexg
Mar 22 '18 at 13:21
git branch -d $(git branch --merged | grep -v master)– alexg
Mar 22 '18 at 13:21
add a comment |
You can add the commit to the --merged option.
This way you can make sure only to remove branches which are merged into i.e. the origin/master
Following command will remove merged branches from your origin.
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete
You can test which branches will be removed replacing the git push origin --delete with echo
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo
1
I like the test option
– iwein
Sep 22 '15 at 9:01
add a comment |
You can add the commit to the --merged option.
This way you can make sure only to remove branches which are merged into i.e. the origin/master
Following command will remove merged branches from your origin.
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete
You can test which branches will be removed replacing the git push origin --delete with echo
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo
1
I like the test option
– iwein
Sep 22 '15 at 9:01
add a comment |
You can add the commit to the --merged option.
This way you can make sure only to remove branches which are merged into i.e. the origin/master
Following command will remove merged branches from your origin.
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete
You can test which branches will be removed replacing the git push origin --delete with echo
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo
You can add the commit to the --merged option.
This way you can make sure only to remove branches which are merged into i.e. the origin/master
Following command will remove merged branches from your origin.
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete
You can test which branches will be removed replacing the git push origin --delete with echo
git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo
edited Jul 8 '14 at 8:42
answered Jul 8 '14 at 6:28
Jörn ReimerdesJörn Reimerdes
40648
40648
1
I like the test option
– iwein
Sep 22 '15 at 9:01
add a comment |
1
I like the test option
– iwein
Sep 22 '15 at 9:01
1
1
I like the test option
– iwein
Sep 22 '15 at 9:01
I like the test option
– iwein
Sep 22 '15 at 9:01
add a comment |
I've used Adam's answer for years now. That said, that there are some cases where it wasn't behaving as I expected:
- branches that contained the word "master" were ignored, e.g. "notmaster" or "masterful", rather than only the master branch
- branches that contained the word "dev" were ignored, e.g. "dev-test", rather than only the dev branch
- deleting branches that are reachable from the HEAD of the current branch (that is, not necessarily master)
- in detached HEAD state, deleting every branch reachable from the current commit
1 & 2 were straightforward to address, with just a change to the regex.
3 depends on the context of what you want (i.e. only delete branches that haven't been merged into master or against your current branch).
4 has the potential to be disastrous (although recoverable with git reflog), if you unintentionally ran this in detached HEAD state.
Finally, I wanted this to all be in a one-liner that didn't require a separate (Bash|Ruby|Python) script.
TL;DR
Create a git alias "sweep" that accepts an optional -f flag:
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
and invoke it with:
git sweep
or:
git sweep -f
The long, detailed answer
It was easiest for me to create an example git repo with some branches and commits to test the correct behavior:
Create a new git repo with a single commit
mkdir sweep-test && cd sweep-test && git init
echo "hello" > hello
git add . && git commit -am "initial commit"
Create some new branches
git branch foo && git branch bar && git branch develop && git branch notmaster && git branch masterful
git branch --list
bar
develop
foo
* master
masterful
notmaster
Desired behavior: select all merged branches except: master, develop or current
The original regex misses the branches "masterful" and "notmaster" :
git checkout foo
git branch --merged | egrep -v "(^*|master|dev)"
bar
With the updated regex (which now excludes "develop" rather than "dev"):
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Switch to branch foo, make a new commit, then checkout a new branch, foobar, based on foo:
echo "foo" > foo
git add . && git commit -am "foo"
git checkout -b foobar
echo "foobar" > foobar
git add . && git commit -am "foobar"
My current branch is foobar, and if I re-run the above command to list the branches I want to delete, the branch "foo" is included even though it hasn't been merged into master:
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
masterful
notmaster
However, if I run the same command on master, the branch "foo" is not included:
git checkout master && git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
And this is simply because git branch --merged defaults to the HEAD of the current branch if not otherwise specified. At least for my workflow, I don't want to delete local branches unless they've been merged to master, so I prefer the following variant:
git checkout foobar
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Detached HEAD state
Relying on the default behavior of git branch --merged has even more significant consequences in detached HEAD state:
git checkout foobar
git checkout HEAD~0
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
foobar
masterful
notmaster
This would have deleted the branch I was just on, "foobar" along with "foo", which is almost certainly not the desired outcome.
With our revised command, however:
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
One line, including the actual delete
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)" | xargs git branch -d
All wrapped up into a git alias "sweep":
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
The alias accepts an optional -f flag. The default behavior is to only delete branches that have been merged into master, but the -f flag will delete branches that have been merged into the current branch.
git sweep
Deleted branch bar (was 9a56952).
Deleted branch masterful (was 9a56952).
Deleted branch notmaster (was 9a56952).
git sweep -f
Deleted branch foo (was 2cea1ab).
add a comment |
I've used Adam's answer for years now. That said, that there are some cases where it wasn't behaving as I expected:
- branches that contained the word "master" were ignored, e.g. "notmaster" or "masterful", rather than only the master branch
- branches that contained the word "dev" were ignored, e.g. "dev-test", rather than only the dev branch
- deleting branches that are reachable from the HEAD of the current branch (that is, not necessarily master)
- in detached HEAD state, deleting every branch reachable from the current commit
1 & 2 were straightforward to address, with just a change to the regex.
3 depends on the context of what you want (i.e. only delete branches that haven't been merged into master or against your current branch).
4 has the potential to be disastrous (although recoverable with git reflog), if you unintentionally ran this in detached HEAD state.
Finally, I wanted this to all be in a one-liner that didn't require a separate (Bash|Ruby|Python) script.
TL;DR
Create a git alias "sweep" that accepts an optional -f flag:
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
and invoke it with:
git sweep
or:
git sweep -f
The long, detailed answer
It was easiest for me to create an example git repo with some branches and commits to test the correct behavior:
Create a new git repo with a single commit
mkdir sweep-test && cd sweep-test && git init
echo "hello" > hello
git add . && git commit -am "initial commit"
Create some new branches
git branch foo && git branch bar && git branch develop && git branch notmaster && git branch masterful
git branch --list
bar
develop
foo
* master
masterful
notmaster
Desired behavior: select all merged branches except: master, develop or current
The original regex misses the branches "masterful" and "notmaster" :
git checkout foo
git branch --merged | egrep -v "(^*|master|dev)"
bar
With the updated regex (which now excludes "develop" rather than "dev"):
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Switch to branch foo, make a new commit, then checkout a new branch, foobar, based on foo:
echo "foo" > foo
git add . && git commit -am "foo"
git checkout -b foobar
echo "foobar" > foobar
git add . && git commit -am "foobar"
My current branch is foobar, and if I re-run the above command to list the branches I want to delete, the branch "foo" is included even though it hasn't been merged into master:
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
masterful
notmaster
However, if I run the same command on master, the branch "foo" is not included:
git checkout master && git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
And this is simply because git branch --merged defaults to the HEAD of the current branch if not otherwise specified. At least for my workflow, I don't want to delete local branches unless they've been merged to master, so I prefer the following variant:
git checkout foobar
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Detached HEAD state
Relying on the default behavior of git branch --merged has even more significant consequences in detached HEAD state:
git checkout foobar
git checkout HEAD~0
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
foobar
masterful
notmaster
This would have deleted the branch I was just on, "foobar" along with "foo", which is almost certainly not the desired outcome.
With our revised command, however:
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
One line, including the actual delete
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)" | xargs git branch -d
All wrapped up into a git alias "sweep":
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
The alias accepts an optional -f flag. The default behavior is to only delete branches that have been merged into master, but the -f flag will delete branches that have been merged into the current branch.
git sweep
Deleted branch bar (was 9a56952).
Deleted branch masterful (was 9a56952).
Deleted branch notmaster (was 9a56952).
git sweep -f
Deleted branch foo (was 2cea1ab).
add a comment |
I've used Adam's answer for years now. That said, that there are some cases where it wasn't behaving as I expected:
- branches that contained the word "master" were ignored, e.g. "notmaster" or "masterful", rather than only the master branch
- branches that contained the word "dev" were ignored, e.g. "dev-test", rather than only the dev branch
- deleting branches that are reachable from the HEAD of the current branch (that is, not necessarily master)
- in detached HEAD state, deleting every branch reachable from the current commit
1 & 2 were straightforward to address, with just a change to the regex.
3 depends on the context of what you want (i.e. only delete branches that haven't been merged into master or against your current branch).
4 has the potential to be disastrous (although recoverable with git reflog), if you unintentionally ran this in detached HEAD state.
Finally, I wanted this to all be in a one-liner that didn't require a separate (Bash|Ruby|Python) script.
TL;DR
Create a git alias "sweep" that accepts an optional -f flag:
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
and invoke it with:
git sweep
or:
git sweep -f
The long, detailed answer
It was easiest for me to create an example git repo with some branches and commits to test the correct behavior:
Create a new git repo with a single commit
mkdir sweep-test && cd sweep-test && git init
echo "hello" > hello
git add . && git commit -am "initial commit"
Create some new branches
git branch foo && git branch bar && git branch develop && git branch notmaster && git branch masterful
git branch --list
bar
develop
foo
* master
masterful
notmaster
Desired behavior: select all merged branches except: master, develop or current
The original regex misses the branches "masterful" and "notmaster" :
git checkout foo
git branch --merged | egrep -v "(^*|master|dev)"
bar
With the updated regex (which now excludes "develop" rather than "dev"):
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Switch to branch foo, make a new commit, then checkout a new branch, foobar, based on foo:
echo "foo" > foo
git add . && git commit -am "foo"
git checkout -b foobar
echo "foobar" > foobar
git add . && git commit -am "foobar"
My current branch is foobar, and if I re-run the above command to list the branches I want to delete, the branch "foo" is included even though it hasn't been merged into master:
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
masterful
notmaster
However, if I run the same command on master, the branch "foo" is not included:
git checkout master && git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
And this is simply because git branch --merged defaults to the HEAD of the current branch if not otherwise specified. At least for my workflow, I don't want to delete local branches unless they've been merged to master, so I prefer the following variant:
git checkout foobar
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Detached HEAD state
Relying on the default behavior of git branch --merged has even more significant consequences in detached HEAD state:
git checkout foobar
git checkout HEAD~0
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
foobar
masterful
notmaster
This would have deleted the branch I was just on, "foobar" along with "foo", which is almost certainly not the desired outcome.
With our revised command, however:
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
One line, including the actual delete
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)" | xargs git branch -d
All wrapped up into a git alias "sweep":
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
The alias accepts an optional -f flag. The default behavior is to only delete branches that have been merged into master, but the -f flag will delete branches that have been merged into the current branch.
git sweep
Deleted branch bar (was 9a56952).
Deleted branch masterful (was 9a56952).
Deleted branch notmaster (was 9a56952).
git sweep -f
Deleted branch foo (was 2cea1ab).
I've used Adam's answer for years now. That said, that there are some cases where it wasn't behaving as I expected:
- branches that contained the word "master" were ignored, e.g. "notmaster" or "masterful", rather than only the master branch
- branches that contained the word "dev" were ignored, e.g. "dev-test", rather than only the dev branch
- deleting branches that are reachable from the HEAD of the current branch (that is, not necessarily master)
- in detached HEAD state, deleting every branch reachable from the current commit
1 & 2 were straightforward to address, with just a change to the regex.
3 depends on the context of what you want (i.e. only delete branches that haven't been merged into master or against your current branch).
4 has the potential to be disastrous (although recoverable with git reflog), if you unintentionally ran this in detached HEAD state.
Finally, I wanted this to all be in a one-liner that didn't require a separate (Bash|Ruby|Python) script.
TL;DR
Create a git alias "sweep" that accepts an optional -f flag:
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
and invoke it with:
git sweep
or:
git sweep -f
The long, detailed answer
It was easiest for me to create an example git repo with some branches and commits to test the correct behavior:
Create a new git repo with a single commit
mkdir sweep-test && cd sweep-test && git init
echo "hello" > hello
git add . && git commit -am "initial commit"
Create some new branches
git branch foo && git branch bar && git branch develop && git branch notmaster && git branch masterful
git branch --list
bar
develop
foo
* master
masterful
notmaster
Desired behavior: select all merged branches except: master, develop or current
The original regex misses the branches "masterful" and "notmaster" :
git checkout foo
git branch --merged | egrep -v "(^*|master|dev)"
bar
With the updated regex (which now excludes "develop" rather than "dev"):
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Switch to branch foo, make a new commit, then checkout a new branch, foobar, based on foo:
echo "foo" > foo
git add . && git commit -am "foo"
git checkout -b foobar
echo "foobar" > foobar
git add . && git commit -am "foobar"
My current branch is foobar, and if I re-run the above command to list the branches I want to delete, the branch "foo" is included even though it hasn't been merged into master:
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
masterful
notmaster
However, if I run the same command on master, the branch "foo" is not included:
git checkout master && git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
And this is simply because git branch --merged defaults to the HEAD of the current branch if not otherwise specified. At least for my workflow, I don't want to delete local branches unless they've been merged to master, so I prefer the following variant:
git checkout foobar
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
Detached HEAD state
Relying on the default behavior of git branch --merged has even more significant consequences in detached HEAD state:
git checkout foobar
git checkout HEAD~0
git branch --merged | egrep -v "(^*|^s*(master|develop)$)"
bar
foo
foobar
masterful
notmaster
This would have deleted the branch I was just on, "foobar" along with "foo", which is almost certainly not the desired outcome.
With our revised command, however:
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
bar
masterful
notmaster
One line, including the actual delete
git branch --merged $(git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)" | xargs git branch -d
All wrapped up into a git alias "sweep":
git config --global alias.sweep '!f(){ git branch --merged $([[ $1 != "-f" ]]
&& git rev-parse master) | egrep -v "(^*|^s*(master|develop)$)"
| xargs git branch -d; }; f'
The alias accepts an optional -f flag. The default behavior is to only delete branches that have been merged into master, but the -f flag will delete branches that have been merged into the current branch.
git sweep
Deleted branch bar (was 9a56952).
Deleted branch masterful (was 9a56952).
Deleted branch notmaster (was 9a56952).
git sweep -f
Deleted branch foo (was 2cea1ab).
edited Aug 8 '18 at 16:22
answered Jul 20 '18 at 6:48
eddieseddies
2,2101625
2,2101625
add a comment |
add a comment |
I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.
#!/usr/bin/env ruby
current_branch = `git symbolic-ref --short HEAD`.chomp
if current_branch != "master"
if $?.exitstatus == 0
puts "WARNING: You are on branch #{current_branch}, NOT master."
else
puts "WARNING: You are not on a branch"
end
puts
end
puts "Fetching merged branches..."
remote_branches= `git branch -r --merged`.
split("n").
map(&:strip).
reject {|b| b =~ //(#{current_branch}|master)/}
local_branches= `git branch --merged`.
gsub(/^* /, '').
split("n").
map(&:strip).
reject {|b| b =~ /(#{current_branch}|master)/}
if remote_branches.empty? && local_branches.empty?
puts "No existing branches have been merged into #{current_branch}."
else
puts "This will remove the following branches:"
puts remote_branches.join("n")
puts local_branches.join("n")
puts "Proceed?"
if gets =~ /^y/i
remote_branches.each do |b|
remote, branch = b.split(///)
`git push #{remote} :#{branch}`
end
# Remove local branches
`git branch -d #{local_branches.join(' ')}`
else
puts "No branches removed."
end
end
Mind if I steal this tidbit for a little git helper library? github.com/yupiq/git-branch-util
– logan
Dec 19 '12 at 22:28
1
Go for it, I wouldn't have put it here if I cared about people reusing the code in some way
– mmrobins
May 20 '13 at 20:56
@mmrobins You have an extra/at the beginning of the reject statement for theremote_branchesline. Is that a typo or does it serve a purpose?
– Jawwad
Jan 27 '16 at 17:46
@mmrobins, oh never mind I see theb.split(///)line now
– Jawwad
Jan 27 '16 at 17:52
If you want to do basically this but via vanilla bash rather than ruby: stackoverflow.com/a/37999948/430128
– Raman
Jun 23 '16 at 19:14
add a comment |
I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.
#!/usr/bin/env ruby
current_branch = `git symbolic-ref --short HEAD`.chomp
if current_branch != "master"
if $?.exitstatus == 0
puts "WARNING: You are on branch #{current_branch}, NOT master."
else
puts "WARNING: You are not on a branch"
end
puts
end
puts "Fetching merged branches..."
remote_branches= `git branch -r --merged`.
split("n").
map(&:strip).
reject {|b| b =~ //(#{current_branch}|master)/}
local_branches= `git branch --merged`.
gsub(/^* /, '').
split("n").
map(&:strip).
reject {|b| b =~ /(#{current_branch}|master)/}
if remote_branches.empty? && local_branches.empty?
puts "No existing branches have been merged into #{current_branch}."
else
puts "This will remove the following branches:"
puts remote_branches.join("n")
puts local_branches.join("n")
puts "Proceed?"
if gets =~ /^y/i
remote_branches.each do |b|
remote, branch = b.split(///)
`git push #{remote} :#{branch}`
end
# Remove local branches
`git branch -d #{local_branches.join(' ')}`
else
puts "No branches removed."
end
end
Mind if I steal this tidbit for a little git helper library? github.com/yupiq/git-branch-util
– logan
Dec 19 '12 at 22:28
1
Go for it, I wouldn't have put it here if I cared about people reusing the code in some way
– mmrobins
May 20 '13 at 20:56
@mmrobins You have an extra/at the beginning of the reject statement for theremote_branchesline. Is that a typo or does it serve a purpose?
– Jawwad
Jan 27 '16 at 17:46
@mmrobins, oh never mind I see theb.split(///)line now
– Jawwad
Jan 27 '16 at 17:52
If you want to do basically this but via vanilla bash rather than ruby: stackoverflow.com/a/37999948/430128
– Raman
Jun 23 '16 at 19:14
add a comment |
I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.
#!/usr/bin/env ruby
current_branch = `git symbolic-ref --short HEAD`.chomp
if current_branch != "master"
if $?.exitstatus == 0
puts "WARNING: You are on branch #{current_branch}, NOT master."
else
puts "WARNING: You are not on a branch"
end
puts
end
puts "Fetching merged branches..."
remote_branches= `git branch -r --merged`.
split("n").
map(&:strip).
reject {|b| b =~ //(#{current_branch}|master)/}
local_branches= `git branch --merged`.
gsub(/^* /, '').
split("n").
map(&:strip).
reject {|b| b =~ /(#{current_branch}|master)/}
if remote_branches.empty? && local_branches.empty?
puts "No existing branches have been merged into #{current_branch}."
else
puts "This will remove the following branches:"
puts remote_branches.join("n")
puts local_branches.join("n")
puts "Proceed?"
if gets =~ /^y/i
remote_branches.each do |b|
remote, branch = b.split(///)
`git push #{remote} :#{branch}`
end
# Remove local branches
`git branch -d #{local_branches.join(' ')}`
else
puts "No branches removed."
end
end
I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.
#!/usr/bin/env ruby
current_branch = `git symbolic-ref --short HEAD`.chomp
if current_branch != "master"
if $?.exitstatus == 0
puts "WARNING: You are on branch #{current_branch}, NOT master."
else
puts "WARNING: You are not on a branch"
end
puts
end
puts "Fetching merged branches..."
remote_branches= `git branch -r --merged`.
split("n").
map(&:strip).
reject {|b| b =~ //(#{current_branch}|master)/}
local_branches= `git branch --merged`.
gsub(/^* /, '').
split("n").
map(&:strip).
reject {|b| b =~ /(#{current_branch}|master)/}
if remote_branches.empty? && local_branches.empty?
puts "No existing branches have been merged into #{current_branch}."
else
puts "This will remove the following branches:"
puts remote_branches.join("n")
puts local_branches.join("n")
puts "Proceed?"
if gets =~ /^y/i
remote_branches.each do |b|
remote, branch = b.split(///)
`git push #{remote} :#{branch}`
end
# Remove local branches
`git branch -d #{local_branches.join(' ')}`
else
puts "No branches removed."
end
end
edited Aug 31 '17 at 23:53
Peter Mortensen
13.7k1986112
13.7k1986112
answered Sep 27 '12 at 23:41
mmrobinsmmrobins
6,02873239
6,02873239
Mind if I steal this tidbit for a little git helper library? github.com/yupiq/git-branch-util
– logan
Dec 19 '12 at 22:28
1
Go for it, I wouldn't have put it here if I cared about people reusing the code in some way
– mmrobins
May 20 '13 at 20:56
@mmrobins You have an extra/at the beginning of the reject statement for theremote_branchesline. Is that a typo or does it serve a purpose?
– Jawwad
Jan 27 '16 at 17:46
@mmrobins, oh never mind I see theb.split(///)line now
– Jawwad
Jan 27 '16 at 17:52
If you want to do basically this but via vanilla bash rather than ruby: stackoverflow.com/a/37999948/430128
– Raman
Jun 23 '16 at 19:14
add a comment |
Mind if I steal this tidbit for a little git helper library? github.com/yupiq/git-branch-util
– logan
Dec 19 '12 at 22:28
1
Go for it, I wouldn't have put it here if I cared about people reusing the code in some way
– mmrobins
May 20 '13 at 20:56
@mmrobins You have an extra/at the beginning of the reject statement for theremote_branchesline. Is that a typo or does it serve a purpose?
– Jawwad
Jan 27 '16 at 17:46
@mmrobins, oh never mind I see theb.split(///)line now
– Jawwad
Jan 27 '16 at 17:52
If you want to do basically this but via vanilla bash rather than ruby: stackoverflow.com/a/37999948/430128
– Raman
Jun 23 '16 at 19:14
Mind if I steal this tidbit for a little git helper library? github.com/yupiq/git-branch-util
– logan
Dec 19 '12 at 22:28
Mind if I steal this tidbit for a little git helper library? github.com/yupiq/git-branch-util
– logan
Dec 19 '12 at 22:28
1
1
Go for it, I wouldn't have put it here if I cared about people reusing the code in some way
– mmrobins
May 20 '13 at 20:56
Go for it, I wouldn't have put it here if I cared about people reusing the code in some way
– mmrobins
May 20 '13 at 20:56
@mmrobins You have an extra
/ at the beginning of the reject statement for the remote_branches line. Is that a typo or does it serve a purpose?– Jawwad
Jan 27 '16 at 17:46
@mmrobins You have an extra
/ at the beginning of the reject statement for the remote_branches line. Is that a typo or does it serve a purpose?– Jawwad
Jan 27 '16 at 17:46
@mmrobins, oh never mind I see the
b.split(///) line now– Jawwad
Jan 27 '16 at 17:52
@mmrobins, oh never mind I see the
b.split(///) line now– Jawwad
Jan 27 '16 at 17:52
If you want to do basically this but via vanilla bash rather than ruby: stackoverflow.com/a/37999948/430128
– Raman
Jun 23 '16 at 19:14
If you want to do basically this but via vanilla bash rather than ruby: stackoverflow.com/a/37999948/430128
– Raman
Jun 23 '16 at 19:14
add a comment |
kuboon's answer missed deleting branches which have the word master in the branch name.
The following improves on his answer:
git branch -r --merged | grep -v "origin/master$" | sed 's/s*origin///' | xargs -n 1 git push --delete origin
Of course, it does not delete the "master" branch itself :)
add a comment |
kuboon's answer missed deleting branches which have the word master in the branch name.
The following improves on his answer:
git branch -r --merged | grep -v "origin/master$" | sed 's/s*origin///' | xargs -n 1 git push --delete origin
Of course, it does not delete the "master" branch itself :)
add a comment |
kuboon's answer missed deleting branches which have the word master in the branch name.
The following improves on his answer:
git branch -r --merged | grep -v "origin/master$" | sed 's/s*origin///' | xargs -n 1 git push --delete origin
Of course, it does not delete the "master" branch itself :)
kuboon's answer missed deleting branches which have the word master in the branch name.
The following improves on his answer:
git branch -r --merged | grep -v "origin/master$" | sed 's/s*origin///' | xargs -n 1 git push --delete origin
Of course, it does not delete the "master" branch itself :)
answered Oct 4 '13 at 6:05
ParasParas
562415
562415
add a comment |
add a comment |
How to delete merged branches in PowerShell console
git branch --merged | %{git branch -d $_.Trim()}
See GitHub for Windows
1
Higher answers are suggesting filtering master or other branches. For those looking to do that in powershell: git branch --merged | findstr /v "master" | %{git branch -d $_.trim()}
– tredzko
Jul 28 '15 at 15:03
@tredzko Good point. FTR the higher answer is stackoverflow.com/questions/6127328/… - you could repost your comment with that linked and I'd then delete this
– Ruben Bartelink
Feb 23 '16 at 11:40
it also tries to delete* master:)
– iesen
Dec 15 '17 at 8:37
add a comment |
How to delete merged branches in PowerShell console
git branch --merged | %{git branch -d $_.Trim()}
See GitHub for Windows
1
Higher answers are suggesting filtering master or other branches. For those looking to do that in powershell: git branch --merged | findstr /v "master" | %{git branch -d $_.trim()}
– tredzko
Jul 28 '15 at 15:03
@tredzko Good point. FTR the higher answer is stackoverflow.com/questions/6127328/… - you could repost your comment with that linked and I'd then delete this
– Ruben Bartelink
Feb 23 '16 at 11:40
it also tries to delete* master:)
– iesen
Dec 15 '17 at 8:37
add a comment |
How to delete merged branches in PowerShell console
git branch --merged | %{git branch -d $_.Trim()}
See GitHub for Windows
How to delete merged branches in PowerShell console
git branch --merged | %{git branch -d $_.Trim()}
See GitHub for Windows
edited Jan 27 '15 at 14:31
answered Jan 27 '15 at 14:17
Konstantin TarkusKonstantin Tarkus
30.6k13116108
30.6k13116108
1
Higher answers are suggesting filtering master or other branches. For those looking to do that in powershell: git branch --merged | findstr /v "master" | %{git branch -d $_.trim()}
– tredzko
Jul 28 '15 at 15:03
@tredzko Good point. FTR the higher answer is stackoverflow.com/questions/6127328/… - you could repost your comment with that linked and I'd then delete this
– Ruben Bartelink
Feb 23 '16 at 11:40
it also tries to delete* master:)
– iesen
Dec 15 '17 at 8:37
add a comment |
1
Higher answers are suggesting filtering master or other branches. For those looking to do that in powershell: git branch --merged | findstr /v "master" | %{git branch -d $_.trim()}
– tredzko
Jul 28 '15 at 15:03
@tredzko Good point. FTR the higher answer is stackoverflow.com/questions/6127328/… - you could repost your comment with that linked and I'd then delete this
– Ruben Bartelink
Feb 23 '16 at 11:40
it also tries to delete* master:)
– iesen
Dec 15 '17 at 8:37
1
1
Higher answers are suggesting filtering master or other branches. For those looking to do that in powershell: git branch --merged | findstr /v "master" | %{git branch -d $_.trim()}
– tredzko
Jul 28 '15 at 15:03
Higher answers are suggesting filtering master or other branches. For those looking to do that in powershell: git branch --merged | findstr /v "master" | %{git branch -d $_.trim()}
– tredzko
Jul 28 '15 at 15:03
@tredzko Good point. FTR the higher answer is stackoverflow.com/questions/6127328/… - you could repost your comment with that linked and I'd then delete this
– Ruben Bartelink
Feb 23 '16 at 11:40
@tredzko Good point. FTR the higher answer is stackoverflow.com/questions/6127328/… - you could repost your comment with that linked and I'd then delete this
– Ruben Bartelink
Feb 23 '16 at 11:40
it also tries to delete
* master :)– iesen
Dec 15 '17 at 8:37
it also tries to delete
* master :)– iesen
Dec 15 '17 at 8:37
add a comment |
There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.
If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)
$ git rev-list master | grep $(git rev-parse myTopicBranch)
You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.
add a comment |
There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.
If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)
$ git rev-list master | grep $(git rev-parse myTopicBranch)
You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.
add a comment |
There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.
If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)
$ git rev-list master | grep $(git rev-parse myTopicBranch)
You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.
There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.
If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)
$ git rev-list master | grep $(git rev-parse myTopicBranch)
You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.
edited Aug 31 '17 at 23:51
Peter Mortensen
13.7k1986112
13.7k1986112
answered May 26 '11 at 7:41
ralphtheninjaralphtheninja
79.4k1785107
79.4k1785107
add a comment |
add a comment |
git branch --merged | grep -Ev '^(. master|*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.
Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.
add a comment |
git branch --merged | grep -Ev '^(. master|*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.
Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.
add a comment |
git branch --merged | grep -Ev '^(. master|*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.
Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.
git branch --merged | grep -Ev '^(. master|*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.
Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.
answered Oct 23 '14 at 21:06
stygerstyger
352212
352212
add a comment |
add a comment |
You can use git-del-br tool.
git-del-br -a
You can install it via pip using
pip install git-del-br
P.S: I am the author of the tool. Any suggestions/feedback are welcome.
@stackoverflow.com/users/100297/martijn-pieters : Why was this answer deleted and downvoted?
– tusharmakkar08
Sep 29 '16 at 16:23
Your answer and tool don't work. I spend a couple hours on it. Nothing.
– SpoiledTechie.com
Nov 15 '17 at 18:55
@SpoiledTechie.com: Can you tell me what problem are you facing exactly? I am using it on a regular basis.
– tusharmakkar08
Nov 16 '17 at 9:53
I can share a screenshot if you want to take this offline? spoiledtechie at that google mail thing. :)
– SpoiledTechie.com
Nov 17 '17 at 16:12
add a comment |
You can use git-del-br tool.
git-del-br -a
You can install it via pip using
pip install git-del-br
P.S: I am the author of the tool. Any suggestions/feedback are welcome.
@stackoverflow.com/users/100297/martijn-pieters : Why was this answer deleted and downvoted?
– tusharmakkar08
Sep 29 '16 at 16:23
Your answer and tool don't work. I spend a couple hours on it. Nothing.
– SpoiledTechie.com
Nov 15 '17 at 18:55
@SpoiledTechie.com: Can you tell me what problem are you facing exactly? I am using it on a regular basis.
– tusharmakkar08
Nov 16 '17 at 9:53
I can share a screenshot if you want to take this offline? spoiledtechie at that google mail thing. :)
– SpoiledTechie.com
Nov 17 '17 at 16:12
add a comment |
You can use git-del-br tool.
git-del-br -a
You can install it via pip using
pip install git-del-br
P.S: I am the author of the tool. Any suggestions/feedback are welcome.
You can use git-del-br tool.
git-del-br -a
You can install it via pip using
pip install git-del-br
P.S: I am the author of the tool. Any suggestions/feedback are welcome.
answered Jul 19 '16 at 18:50
tusharmakkar08tusharmakkar08
4871828
4871828
@stackoverflow.com/users/100297/martijn-pieters : Why was this answer deleted and downvoted?
– tusharmakkar08
Sep 29 '16 at 16:23
Your answer and tool don't work. I spend a couple hours on it. Nothing.
– SpoiledTechie.com
Nov 15 '17 at 18:55
@SpoiledTechie.com: Can you tell me what problem are you facing exactly? I am using it on a regular basis.
– tusharmakkar08
Nov 16 '17 at 9:53
I can share a screenshot if you want to take this offline? spoiledtechie at that google mail thing. :)
– SpoiledTechie.com
Nov 17 '17 at 16:12
add a comment |
@stackoverflow.com/users/100297/martijn-pieters : Why was this answer deleted and downvoted?
– tusharmakkar08
Sep 29 '16 at 16:23
Your answer and tool don't work. I spend a couple hours on it. Nothing.
– SpoiledTechie.com
Nov 15 '17 at 18:55
@SpoiledTechie.com: Can you tell me what problem are you facing exactly? I am using it on a regular basis.
– tusharmakkar08
Nov 16 '17 at 9:53
I can share a screenshot if you want to take this offline? spoiledtechie at that google mail thing. :)
– SpoiledTechie.com
Nov 17 '17 at 16:12
@stackoverflow.com/users/100297/martijn-pieters : Why was this answer deleted and downvoted?
– tusharmakkar08
Sep 29 '16 at 16:23
@stackoverflow.com/users/100297/martijn-pieters : Why was this answer deleted and downvoted?
– tusharmakkar08
Sep 29 '16 at 16:23
Your answer and tool don't work. I spend a couple hours on it. Nothing.
– SpoiledTechie.com
Nov 15 '17 at 18:55
Your answer and tool don't work. I spend a couple hours on it. Nothing.
– SpoiledTechie.com
Nov 15 '17 at 18:55
@SpoiledTechie.com: Can you tell me what problem are you facing exactly? I am using it on a regular basis.
– tusharmakkar08
Nov 16 '17 at 9:53
@SpoiledTechie.com: Can you tell me what problem are you facing exactly? I am using it on a regular basis.
– tusharmakkar08
Nov 16 '17 at 9:53
I can share a screenshot if you want to take this offline? spoiledtechie at that google mail thing. :)
– SpoiledTechie.com
Nov 17 '17 at 16:12
I can share a screenshot if you want to take this offline? spoiledtechie at that google mail thing. :)
– SpoiledTechie.com
Nov 17 '17 at 16:12
add a comment |
Alias version of Adam's updated answer:
[alias]
branch-cleanup = "!git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d #"
Also, see this answer for handy tips on escaping complex aliases.
add a comment |
Alias version of Adam's updated answer:
[alias]
branch-cleanup = "!git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d #"
Also, see this answer for handy tips on escaping complex aliases.
add a comment |
Alias version of Adam's updated answer:
[alias]
branch-cleanup = "!git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d #"
Also, see this answer for handy tips on escaping complex aliases.
Alias version of Adam's updated answer:
[alias]
branch-cleanup = "!git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d #"
Also, see this answer for handy tips on escaping complex aliases.
edited May 23 '17 at 12:10
Community♦
11
11
answered Sep 30 '16 at 19:54
EliotEliot
3,48022027
3,48022027
add a comment |
add a comment |
If you'd like to delete all local branches that are already merged in to the branch that you are currently on, then I've come up with a safe command to do so, based on earlier answers:
git branch --merged | grep -v * | grep -v '^s*master$' | xargs -t -n 1 git branch -d
This command will not affect your current branch or your master branch. It will also tell you what it's doing before it does it, using the -t flag of xargs.
add a comment |
If you'd like to delete all local branches that are already merged in to the branch that you are currently on, then I've come up with a safe command to do so, based on earlier answers:
git branch --merged | grep -v * | grep -v '^s*master$' | xargs -t -n 1 git branch -d
This command will not affect your current branch or your master branch. It will also tell you what it's doing before it does it, using the -t flag of xargs.
add a comment |
If you'd like to delete all local branches that are already merged in to the branch that you are currently on, then I've come up with a safe command to do so, based on earlier answers:
git branch --merged | grep -v * | grep -v '^s*master$' | xargs -t -n 1 git branch -d
This command will not affect your current branch or your master branch. It will also tell you what it's doing before it does it, using the -t flag of xargs.
If you'd like to delete all local branches that are already merged in to the branch that you are currently on, then I've come up with a safe command to do so, based on earlier answers:
git branch --merged | grep -v * | grep -v '^s*master$' | xargs -t -n 1 git branch -d
This command will not affect your current branch or your master branch. It will also tell you what it's doing before it does it, using the -t flag of xargs.
answered Jan 23 '14 at 16:24
chrismendischrismendis
612
612
add a comment |
add a comment |
Try the following command:
git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.
To do the same with remote branches (change origin with your remote name), try:
git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
In case you've multiple remotes, add grep origin | before cut to filter only the origin.
If above command fails, try to delete the merged remote-tracking branches first:
git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
Then git fetch the remote again and use the previous git push -vdcommand again.
If you're using it often, consider adding as aliases into your ~/.gitconfig file.
In case you've removed some branches by mistake, use git reflog to find the lost commits.
add a comment |
Try the following command:
git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.
To do the same with remote branches (change origin with your remote name), try:
git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
In case you've multiple remotes, add grep origin | before cut to filter only the origin.
If above command fails, try to delete the merged remote-tracking branches first:
git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
Then git fetch the remote again and use the previous git push -vdcommand again.
If you're using it often, consider adding as aliases into your ~/.gitconfig file.
In case you've removed some branches by mistake, use git reflog to find the lost commits.
add a comment |
Try the following command:
git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.
To do the same with remote branches (change origin with your remote name), try:
git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
In case you've multiple remotes, add grep origin | before cut to filter only the origin.
If above command fails, try to delete the merged remote-tracking branches first:
git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
Then git fetch the remote again and use the previous git push -vdcommand again.
If you're using it often, consider adding as aliases into your ~/.gitconfig file.
In case you've removed some branches by mistake, use git reflog to find the lost commits.
Try the following command:
git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.
To do the same with remote branches (change origin with your remote name), try:
git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
In case you've multiple remotes, add grep origin | before cut to filter only the origin.
If above command fails, try to delete the merged remote-tracking branches first:
git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
Then git fetch the remote again and use the previous git push -vdcommand again.
If you're using it often, consider adding as aliases into your ~/.gitconfig file.
In case you've removed some branches by mistake, use git reflog to find the lost commits.
edited May 23 '17 at 11:55
Community♦
11
11
answered Dec 17 '16 at 12:17
kenorbkenorb
68.7k29406406
68.7k29406406
add a comment |
add a comment |
Based on some of these answers I made my own Bash script to do it too!
It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.
merged_branches(){
local current_branch=$(git rev-parse --abbrev-ref HEAD)
for branch in $(git branch --merged | cut -c3-)
do
echo "Branch $branch is already merged into $current_branch."
echo "Would you like to delete it? [Y]es/[N]o "
read REPLY
if [[ $REPLY =~ ^[Yy] ]]; then
git branch -d $branch
fi
done
}
add a comment |
Based on some of these answers I made my own Bash script to do it too!
It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.
merged_branches(){
local current_branch=$(git rev-parse --abbrev-ref HEAD)
for branch in $(git branch --merged | cut -c3-)
do
echo "Branch $branch is already merged into $current_branch."
echo "Would you like to delete it? [Y]es/[N]o "
read REPLY
if [[ $REPLY =~ ^[Yy] ]]; then
git branch -d $branch
fi
done
}
add a comment |
Based on some of these answers I made my own Bash script to do it too!
It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.
merged_branches(){
local current_branch=$(git rev-parse --abbrev-ref HEAD)
for branch in $(git branch --merged | cut -c3-)
do
echo "Branch $branch is already merged into $current_branch."
echo "Would you like to delete it? [Y]es/[N]o "
read REPLY
if [[ $REPLY =~ ^[Yy] ]]; then
git branch -d $branch
fi
done
}
Based on some of these answers I made my own Bash script to do it too!
It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.
merged_branches(){
local current_branch=$(git rev-parse --abbrev-ref HEAD)
for branch in $(git branch --merged | cut -c3-)
do
echo "Branch $branch is already merged into $current_branch."
echo "Would you like to delete it? [Y]es/[N]o "
read REPLY
if [[ $REPLY =~ ^[Yy] ]]; then
git branch -d $branch
fi
done
}
edited Aug 31 '17 at 23:56
Peter Mortensen
13.7k1986112
13.7k1986112
answered Oct 15 '13 at 17:13
earlonrailsearlonrails
3,54012243
3,54012243
add a comment |
add a comment |
I use a git-flow esque naming scheme, so this works very safely for me:
git branch --merged | grep -e "^s+(fix|feature)/" | xargs git branch -d
It basically looks for merged commits that start with either string fix/ or feature/.
add a comment |
I use a git-flow esque naming scheme, so this works very safely for me:
git branch --merged | grep -e "^s+(fix|feature)/" | xargs git branch -d
It basically looks for merged commits that start with either string fix/ or feature/.
add a comment |
I use a git-flow esque naming scheme, so this works very safely for me:
git branch --merged | grep -e "^s+(fix|feature)/" | xargs git branch -d
It basically looks for merged commits that start with either string fix/ or feature/.
I use a git-flow esque naming scheme, so this works very safely for me:
git branch --merged | grep -e "^s+(fix|feature)/" | xargs git branch -d
It basically looks for merged commits that start with either string fix/ or feature/.
edited Sep 1 '17 at 0:01
Peter Mortensen
13.7k1986112
13.7k1986112
answered Aug 23 '16 at 1:15
Chad MChad M
463617
463617
add a comment |
add a comment |
Below query works for me
for branch in `git branch -r --merged | grep -v '*|master|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin//, "")}1'`;do git push origin --delete $branch; done
and this will filter any given branch in the grep pipe.
Works well over http clone, but not so well for the ssh connection.
add a comment |
Below query works for me
for branch in `git branch -r --merged | grep -v '*|master|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin//, "")}1'`;do git push origin --delete $branch; done
and this will filter any given branch in the grep pipe.
Works well over http clone, but not so well for the ssh connection.
add a comment |
Below query works for me
for branch in `git branch -r --merged | grep -v '*|master|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin//, "")}1'`;do git push origin --delete $branch; done
and this will filter any given branch in the grep pipe.
Works well over http clone, but not so well for the ssh connection.
Below query works for me
for branch in `git branch -r --merged | grep -v '*|master|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin//, "")}1'`;do git push origin --delete $branch; done
and this will filter any given branch in the grep pipe.
Works well over http clone, but not so well for the ssh connection.
answered Jan 19 '18 at 10:50
user1460965user1460965
411
411
add a comment |
add a comment |
Write a script in which Git checks out all the branches that have been merged to master.
Then do git checkout master.
Finally, delete the merged branches.
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git checkout $branchnew
done
git checkout master
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git push origin --delete $branchnew
done
add a comment |
Write a script in which Git checks out all the branches that have been merged to master.
Then do git checkout master.
Finally, delete the merged branches.
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git checkout $branchnew
done
git checkout master
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git push origin --delete $branchnew
done
add a comment |
Write a script in which Git checks out all the branches that have been merged to master.
Then do git checkout master.
Finally, delete the merged branches.
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git checkout $branchnew
done
git checkout master
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git push origin --delete $branchnew
done
Write a script in which Git checks out all the branches that have been merged to master.
Then do git checkout master.
Finally, delete the merged branches.
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git checkout $branchnew
done
git checkout master
for k in $(git branch -ra --merged | egrep -v "(^*|master)"); do
branchnew=$(echo $k | sed -e "s/origin///" | sed -e "s/remotes///")
echo branch-name: $branchnew
git push origin --delete $branchnew
done
edited Sep 1 '17 at 0:03
Peter Mortensen
13.7k1986112
13.7k1986112
answered Aug 9 '17 at 13:42
KomuKomu
7,50621812
7,50621812
add a comment |
add a comment |
The accepted solution is pretty good, but has the one issue that it also deletes local branches that were not yet merged into a remote.
If you look at the output of you will see something like
$ git branch --merged master -v
api_doc 3a05427 [gone] Start of describing the Java API
bla 52e080a Update wording.
branch-1.0 32f1a72 [maven-release-plugin] prepare release 1.0.1
initial_proposal 6e59fb0 [gone] Original proposal, converted to AsciiDoc.
issue_248 be2ba3c Skip unit-for-type checking. This needs more work. (#254)
master be2ba3c Skip unit-for-type checking. This needs more work. (#254)
Branches bla and issue_248 are local branches that would be deleted silently.
But you can also see the word [gone], which indicate branches that had been pushed to a remote (which is now gone) and thus denote branches can be deleted.
The original answer can thus be changed to (split into multiline for shorter line length)
git branch --merged master -v |
grep "\[gone\]" |
sed -e 's/^..//' -e 's/S* .*//' |
xargs git branch -d
to protect the not yet merged branches.
Also the grepping for master to protect it, is not needed, as this has a remote at origin and does not show up as gone.
add a comment |
The accepted solution is pretty good, but has the one issue that it also deletes local branches that were not yet merged into a remote.
If you look at the output of you will see something like
$ git branch --merged master -v
api_doc 3a05427 [gone] Start of describing the Java API
bla 52e080a Update wording.
branch-1.0 32f1a72 [maven-release-plugin] prepare release 1.0.1
initial_proposal 6e59fb0 [gone] Original proposal, converted to AsciiDoc.
issue_248 be2ba3c Skip unit-for-type checking. This needs more work. (#254)
master be2ba3c Skip unit-for-type checking. This needs more work. (#254)
Branches bla and issue_248 are local branches that would be deleted silently.
But you can also see the word [gone], which indicate branches that had been pushed to a remote (which is now gone) and thus denote branches can be deleted.
The original answer can thus be changed to (split into multiline for shorter line length)
git branch --merged master -v |
grep "\[gone\]" |
sed -e 's/^..//' -e 's/S* .*//' |
xargs git branch -d
to protect the not yet merged branches.
Also the grepping for master to protect it, is not needed, as this has a remote at origin and does not show up as gone.
add a comment |
The accepted solution is pretty good, but has the one issue that it also deletes local branches that were not yet merged into a remote.
If you look at the output of you will see something like
$ git branch --merged master -v
api_doc 3a05427 [gone] Start of describing the Java API
bla 52e080a Update wording.
branch-1.0 32f1a72 [maven-release-plugin] prepare release 1.0.1
initial_proposal 6e59fb0 [gone] Original proposal, converted to AsciiDoc.
issue_248 be2ba3c Skip unit-for-type checking. This needs more work. (#254)
master be2ba3c Skip unit-for-type checking. This needs more work. (#254)
Branches bla and issue_248 are local branches that would be deleted silently.
But you can also see the word [gone], which indicate branches that had been pushed to a remote (which is now gone) and thus denote branches can be deleted.
The original answer can thus be changed to (split into multiline for shorter line length)
git branch --merged master -v |
grep "\[gone\]" |
sed -e 's/^..//' -e 's/S* .*//' |
xargs git branch -d
to protect the not yet merged branches.
Also the grepping for master to protect it, is not needed, as this has a remote at origin and does not show up as gone.
The accepted solution is pretty good, but has the one issue that it also deletes local branches that were not yet merged into a remote.
If you look at the output of you will see something like
$ git branch --merged master -v
api_doc 3a05427 [gone] Start of describing the Java API
bla 52e080a Update wording.
branch-1.0 32f1a72 [maven-release-plugin] prepare release 1.0.1
initial_proposal 6e59fb0 [gone] Original proposal, converted to AsciiDoc.
issue_248 be2ba3c Skip unit-for-type checking. This needs more work. (#254)
master be2ba3c Skip unit-for-type checking. This needs more work. (#254)
Branches bla and issue_248 are local branches that would be deleted silently.
But you can also see the word [gone], which indicate branches that had been pushed to a remote (which is now gone) and thus denote branches can be deleted.
The original answer can thus be changed to (split into multiline for shorter line length)
git branch --merged master -v |
grep "\[gone\]" |
sed -e 's/^..//' -e 's/S* .*//' |
xargs git branch -d
to protect the not yet merged branches.
Also the grepping for master to protect it, is not needed, as this has a remote at origin and does not show up as gone.
answered Jun 15 '18 at 8:53
Heiko RuppHeiko Rupp
22.5k1271114
22.5k1271114
add a comment |
add a comment |
To avoid accidentally running the command from any other branch than master I use the following bash script. Otherwise, running git branch --merged | grep -v "*" | xargs -n 1 git branch -d from a branch that has been merged of off master could delete the master branch.
#!/bin/bash
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
if [[ $branch_name == 'master' ]]; then
read -r -p "Are you sure? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
git branch --merged | grep -v "*" | xargs -n 1 git branch -d
fi
else
echo "Refusing to delete branches that are not merged into '$branch_name'. Checkout master first."
fi
add a comment |
To avoid accidentally running the command from any other branch than master I use the following bash script. Otherwise, running git branch --merged | grep -v "*" | xargs -n 1 git branch -d from a branch that has been merged of off master could delete the master branch.
#!/bin/bash
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
if [[ $branch_name == 'master' ]]; then
read -r -p "Are you sure? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
git branch --merged | grep -v "*" | xargs -n 1 git branch -d
fi
else
echo "Refusing to delete branches that are not merged into '$branch_name'. Checkout master first."
fi
add a comment |
To avoid accidentally running the command from any other branch than master I use the following bash script. Otherwise, running git branch --merged | grep -v "*" | xargs -n 1 git branch -d from a branch that has been merged of off master could delete the master branch.
#!/bin/bash
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
if [[ $branch_name == 'master' ]]; then
read -r -p "Are you sure? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
git branch --merged | grep -v "*" | xargs -n 1 git branch -d
fi
else
echo "Refusing to delete branches that are not merged into '$branch_name'. Checkout master first."
fi
To avoid accidentally running the command from any other branch than master I use the following bash script. Otherwise, running git branch --merged | grep -v "*" | xargs -n 1 git branch -d from a branch that has been merged of off master could delete the master branch.
#!/bin/bash
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
if [[ $branch_name == 'master' ]]; then
read -r -p "Are you sure? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
git branch --merged | grep -v "*" | xargs -n 1 git branch -d
fi
else
echo "Refusing to delete branches that are not merged into '$branch_name'. Checkout master first."
fi
edited Jan 20 '14 at 17:19
answered Jan 20 '14 at 17:05
Robert KajicRobert Kajic
6,13023339
6,13023339
add a comment |
add a comment |
As of 2018.07
Add this to [alias] section of your ~/.gitconfig:
sweep = !"f() { git branch --merged | egrep -v "(^\*|master|dev)" || true | xargs git branch -d; }; f"
Now you can just call git sweep to perform that needed cleanup.
For me, calling git sweep only lists the branches that should be cleaned up, but it does not remove them
– Victor Moraes
Jul 5 '18 at 20:26
add a comment |
As of 2018.07
Add this to [alias] section of your ~/.gitconfig:
sweep = !"f() { git branch --merged | egrep -v "(^\*|master|dev)" || true | xargs git branch -d; }; f"
Now you can just call git sweep to perform that needed cleanup.
For me, calling git sweep only lists the branches that should be cleaned up, but it does not remove them
– Victor Moraes
Jul 5 '18 at 20:26
add a comment |
As of 2018.07
Add this to [alias] section of your ~/.gitconfig:
sweep = !"f() { git branch --merged | egrep -v "(^\*|master|dev)" || true | xargs git branch -d; }; f"
Now you can just call git sweep to perform that needed cleanup.
As of 2018.07
Add this to [alias] section of your ~/.gitconfig:
sweep = !"f() { git branch --merged | egrep -v "(^\*|master|dev)" || true | xargs git branch -d; }; f"
Now you can just call git sweep to perform that needed cleanup.
answered Jul 1 '18 at 7:49
sorinsorin
75.5k116372582
75.5k116372582
For me, calling git sweep only lists the branches that should be cleaned up, but it does not remove them
– Victor Moraes
Jul 5 '18 at 20:26
add a comment |
For me, calling git sweep only lists the branches that should be cleaned up, but it does not remove them
– Victor Moraes
Jul 5 '18 at 20:26
For me, calling git sweep only lists the branches that should be cleaned up, but it does not remove them
– Victor Moraes
Jul 5 '18 at 20:26
For me, calling git sweep only lists the branches that should be cleaned up, but it does not remove them
– Victor Moraes
Jul 5 '18 at 20:26
add a comment |
On Windows with git bash installed egrep -v will not work
git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
where grep -E -v is equivalent of egrep -v
Use -d to remove already merged branches or
-D to remove unmerged branches
egrep -v works for me. I'm using gitbash from the gitextensions installer though
– Joe Phillips
Jul 10 '18 at 16:47
add a comment |
On Windows with git bash installed egrep -v will not work
git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
where grep -E -v is equivalent of egrep -v
Use -d to remove already merged branches or
-D to remove unmerged branches
egrep -v works for me. I'm using gitbash from the gitextensions installer though
– Joe Phillips
Jul 10 '18 at 16:47
add a comment |
On Windows with git bash installed egrep -v will not work
git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
where grep -E -v is equivalent of egrep -v
Use -d to remove already merged branches or
-D to remove unmerged branches
On Windows with git bash installed egrep -v will not work
git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
where grep -E -v is equivalent of egrep -v
Use -d to remove already merged branches or
-D to remove unmerged branches
edited Aug 13 '18 at 1:55
eddies
2,2101625
2,2101625
answered May 23 '18 at 2:23
DevWLDevWL
6,56025053
6,56025053
egrep -v works for me. I'm using gitbash from the gitextensions installer though
– Joe Phillips
Jul 10 '18 at 16:47
add a comment |
egrep -v works for me. I'm using gitbash from the gitextensions installer though
– Joe Phillips
Jul 10 '18 at 16:47
egrep -v works for me. I'm using gitbash from the gitextensions installer though
– Joe Phillips
Jul 10 '18 at 16:47
egrep -v works for me. I'm using gitbash from the gitextensions installer though
– Joe Phillips
Jul 10 '18 at 16:47
add a comment |
For Windows you can install Cygwin and remove all remote branches using following command:
git branch -r --merged | "C:cygwin64bingrep.exe" -v master | "C:cygwin64binsed.exe" 's/origin///' | "C:cygwin64binxargs.exe" -n 1 git push --delete origin
add a comment |
For Windows you can install Cygwin and remove all remote branches using following command:
git branch -r --merged | "C:cygwin64bingrep.exe" -v master | "C:cygwin64binsed.exe" 's/origin///' | "C:cygwin64binxargs.exe" -n 1 git push --delete origin
add a comment |
For Windows you can install Cygwin and remove all remote branches using following command:
git branch -r --merged | "C:cygwin64bingrep.exe" -v master | "C:cygwin64binsed.exe" 's/origin///' | "C:cygwin64binxargs.exe" -n 1 git push --delete origin
For Windows you can install Cygwin and remove all remote branches using following command:
git branch -r --merged | "C:cygwin64bingrep.exe" -v master | "C:cygwin64binsed.exe" 's/origin///' | "C:cygwin64binxargs.exe" -n 1 git push --delete origin
answered Sep 9 '18 at 7:17
Seyed Morteza MousaviSeyed Morteza Mousavi
3,08262951
3,08262951
add a comment |
add a comment |
To delete local branches that have been merged to master branch I'm using the following alias (git config -e --global):
cleanup = "!git branch --merged master | grep -v '^*\|master' | xargs -n 1 git branch -D"
I'm using git branch -D to avoid error: The branch 'some-branch' is not fully merged. messages while my current checkout is different from master branch.
add a comment |
To delete local branches that have been merged to master branch I'm using the following alias (git config -e --global):
cleanup = "!git branch --merged master | grep -v '^*\|master' | xargs -n 1 git branch -D"
I'm using git branch -D to avoid error: The branch 'some-branch' is not fully merged. messages while my current checkout is different from master branch.
add a comment |
To delete local branches that have been merged to master branch I'm using the following alias (git config -e --global):
cleanup = "!git branch --merged master | grep -v '^*\|master' | xargs -n 1 git branch -D"
I'm using git branch -D to avoid error: The branch 'some-branch' is not fully merged. messages while my current checkout is different from master branch.
To delete local branches that have been merged to master branch I'm using the following alias (git config -e --global):
cleanup = "!git branch --merged master | grep -v '^*\|master' | xargs -n 1 git branch -D"
I'm using git branch -D to avoid error: The branch 'some-branch' is not fully merged. messages while my current checkout is different from master branch.
answered Oct 9 '14 at 8:45
dgtdgt
66266
66266
add a comment |
add a comment |
Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):
#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
# git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain
import gitapi
repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('n'):
branch = branch.strip()
if branch.strip(' *') != 'master':
print(repo.git_command('branch', '-d', branch).strip())
https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc
add a comment |
Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):
#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
# git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain
import gitapi
repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('n'):
branch = branch.strip()
if branch.strip(' *') != 'master':
print(repo.git_command('branch', '-d', branch).strip())
https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc
add a comment |
Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):
#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
# git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain
import gitapi
repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('n'):
branch = branch.strip()
if branch.strip(' *') != 'master':
print(repo.git_command('branch', '-d', branch).strip())
https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc
Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):
#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
# git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain
import gitapi
repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('n'):
branch = branch.strip()
if branch.strip(' *') != 'master':
print(repo.git_command('branch', '-d', branch).strip())
https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc
answered Jan 6 '15 at 18:52
anatoly techtonikanatoly techtonik
11.9k586101
11.9k586101
add a comment |
add a comment |
1 2
next
protected by coldspeed Dec 20 '18 at 4:45
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
35
git branch -D deletes branches that have NOT been merged! Use with care!
– Dan Solovay
Dec 23 '16 at 14:05
27
To be slightly more specific
git branch -Ddeletes any branch whether it as been merged or not.– PhilT
Feb 8 '17 at 9:48
6
You can also do this directly from GitHub, if you go to the 'branches' section of your repo (e.g. github.com/<username>/<repo_name>/branches). There should be a list of all your branches, with a red trashcan icon on the side which will delete the selected branch. Much faster than doing it in the terminal! Will also show how far ahead/behind
mastereach branch is. However, your local client will still list the old branches if you rungit branch -a; usegit fetch --pruneto remove them (as per this answer ).– user5359531
Feb 24 '17 at 16:13
2
Script to do this locally or remotely - with safety checks and pre-configured "safe branches": github.com/fatso83/dotfiles/tree/master/utils/…
git delete-merged --doit originorgit delete-merged --doit --local– oligofren
Jun 27 '17 at 15:10
You could also use this app to auto delete merged branches.
– Sebass van Boxel
Aug 7 '18 at 16:16