Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Remove merged branches from your local machine
Tom Nijhof
Tom Nijhof

Posted on • Edited on

     

Remove merged branches from your local machine

Image description

Remove merged branches from your local machine

If you work with a remote Git repository, you might encounter a situation where you still have branches on your local machine, but those branches have been removed from the remote repository.

  • Open a bash terminal (if you are on Windows you will have git bash. CMD, and PowerShell will not work).

  • Run the following command:

    git fetch-p&& git branch-vv |awk'/: gone]/{print $1}' | xargs git branch-d

Let’s break down the command:

git fetch -p: This command fetches the branches and their commits from the remote repository to your local repository. The -p or --prune option removes any remote-tracking references (i.e., origin/branch-name) to branches that have been deleted on the remote repository.

&&: This is a logical AND operator. In the context of command-line operations, it means “execute the following command only if the previous command succeeded.”

git branch -vv: This command lists all local branches and their upstream branches. If a local branch’s upstream branch has been deleted, it will show [gone] next to it.

An example where `deleted-branch` is deleted, `only-local-branch` was never pushed to the remote repository, and `main` and `test-branch` are both local and remote.
An example wheredeleted-branch is deleted,only-local-branch was never pushed to the remote repository, andmain andtest-branch are both local and remote.

|awk '/:gone]/{print $1}': This part of the command pipes (|) the output of the previous command to awk, a text processing utility. The awk command is programmed to match lines containing:gone] and print the first field ($1) of those lines, which is the branch name.

The result of command so far given me only `deleted-branch`
The result ofgit fetch -p && git branch -vv | awk ‘/: gone]/{print $1}’ given me onlydeleted-branch

| xargs git branch -d: This part of the command pipes the output of the previous command (i.e., the names of the branches to be deleted) to xargs, which executes the git branch-d command for each input. Thegit branch -d command deletes a branch.

So, in summary, this command fetches updates from the remote repository, identifies local branches whose upstream branches have been deleted, and deletes those local branches.

Bonus

This is the error if you try to run itduring a merge

A screenshot showing the error message error: The branch 'branch name' is not fully merged.

Top comments(24)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️
Blog: https://blog.but.gayMastodon: @darkwiiplayer@tech.lgbtPronouns: en.pronouns.page/@darkwiiplayer
  • Pronouns
    she/her;q=1, they/them;q=0.8, */*;q=0.2
  • Joined

Cool script, but personally I would feel a bit paranoid about just yeeting branches like that. I'd probably drop this into a script and make it so it opens a list of commands in vim or something so I could individually decide if I want to keep any of them after all

CollapseExpand
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

It does check if the branches are related to a "gone" origin branch. If you have a branch without origin, it will stay. So only if the origin branch is merged or delete it will delete the local one

CollapseExpand
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️
Blog: https://blog.but.gayMastodon: @darkwiiplayer@tech.lgbtPronouns: en.pronouns.page/@darkwiiplayer
  • Pronouns
    she/her;q=1, they/them;q=0.8, */*;q=0.2
  • Joined

Yea, but I can think of cases where that might happen where you still wouldn't want to delete the local branch. Knowing myself, I just think this looks like a massive foot-gun, and I'd add some safety features to protect myself from myself.

Thread Thread
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

Do you not work with feature branches? I normally make a branch for a feature and when I am done with it I merge

But in the name of science!! I added a commit to a local branch where the remote was merged and deleted. It gave me this error:
Image description
Meaning it is not possible to delete local branches that are commits ahead

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️
Blog: https://blog.but.gayMastodon: @darkwiiplayer@tech.lgbtPronouns: en.pronouns.page/@darkwiiplayer
  • Pronouns
    she/her;q=1, they/them;q=0.8, */*;q=0.2
  • Joined

What if you create a branch for local use, push it by accident and delete it from the remote repository again? Wouldn't that then cause the local branch to get deleted as well?

Thread Thread
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

Not if there are still commits on the branch, it will give the same error withnot fully merged

CollapseExpand
 
joolsmcfly profile image
Julien Dephix
Been programming for over 20 years and loving it!
  • Location
    France
  • Work
    Full stack Lead Developer
  • Joined

And if you're using a JetBrains product you have the simple and effectiveGit Branch Cleaner plugin.
I mapped it to Ctrl+Shift+Alt+Delete so I get a modal which lists local branches that no longer have their remote equivalent. "select all" and "delete". Done!

CollapseExpand
 
tiuwill profile image
Willian Ferreira Moya
Helping Java Spring developers to improve their applications so they can have less headache detecting problems in production.
  • Location
    Uberlândia, MG, Brazil
  • Work
    Backend developer
  • Joined

Thanks! That's a great tip!
I'll start cleaning up my local branchs. My local branchs are a total mess, I'm starting to get loss on thing that I'm not working anymore, and this will help me do that fast!

CollapseExpand
 
dfabiolb profile image
Fábio Luiz Barbosa
Just trying to survive between 0s and 1s
  • Location
    Curitiba
  • Work
    Infrastructure Analyst
  • Joined

I'm not sure how this will help, but I might be able to translate it to a PowerShell version if there is someone interested in that works a few tries and for the challenge as well. The main issue for me was how I could convertawk andxargs so far shorter that I was able to reach it was something like this:

git fetch -p; git branch -vv | ForEach-Object { if ($_ -match ':\s+gone\]') { git branch -d $_.Split(' ')[2] } }
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

Thank you! Very useful for PowerShell users!!

CollapseExpand
 
jeremysawesome profile image
Jeremiah Smith
  • Joined

This will work for PowerShell, causeposh-git is the bestest. Update it for your own use case (i.e. swapmaster formain). Also - I keep the first run as a lowercase-d and just scan the proposed branches to delete before I swap thegit branch -d command to use a-D and run again.

git checkout master; git remote update origin --prune; git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % {git branch -d $_}
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
pixelrella profile image
Pixelrella
  • Location
    Sweden
  • Pronouns
    She/Her
  • Work
    Developer Experience Engineer
  • Joined

Thanks for sharing! I appreciate that you took the time to break down the different parts of the commands. Your explanations were clear and concise.
Thanks to your descriptions, piping finally makes sense for me💡

CollapseExpand
 
benajaero profile image
ben ajaero
Full Stack Developer and UI / UX Web Designer
  • Location
    Australia
  • Joined

Thank you for the informative tutorial Tom!

This is definitely a useful workflow to clean things up.

I've been in situations where a branch is removed from origin but still exists locally, causing confusion down the line. Please keep up the great content. I'll be sure to check out other articles on your blog!

CollapseExpand
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

I will move my other articles too, the community interaction here is exactly what I missed on Medium!
Thank you all for a warm welcome

CollapseExpand
 
tnypxl profile image
tnypxl
I write code.
  • Joined

Might be a great command for running at the end of every year on a cron job or something.

CollapseExpand
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

I like to do it manually, given that I want to be in control of deleting actions. But I will not stop you from living life more dangerous!

CollapseExpand
 
tnypxl profile image
tnypxl
I write code.
  • Joined

I’m trying to automate my life away over here.

CollapseExpand
 
jnareb profile image
Jakub Narębski
  • Location
    Toruń, Poland
  • Education
    Ph.D. in Physics
  • Pronouns
    he/him
  • Work
    Assistant Professor at Nicolaus Copernicus University in Toruń, Poland
  • Joined

You have perfectly finegit for-each-ref for scripting; why usegit branch -vv intended for user output and then extracting data with awk?

CollapseExpand
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

Simple: I did not though of it

CollapseExpand
 
thomasbnt profile image
Thomas Bnt
French web developer mainly but touches everything. Volunteer admin mod here at DEV. I learn Nuxt at this moment and databases. — Addict to Cappuccino and Music
  • Location
    France
  • Pronouns
    He/him
  • Joined

Thanks for this information!
You have a little typo error with the markdown image 🙌

CollapseExpand
 
wagenrace profile image
Tom Nijhof
I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

Thanks for pointing it out, I think all of them are gone now. Was a bit more than one

Some comments may only be visible to logged-in visitors.Sign in to view all comments.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a developer mainly dealing with Python, Javascript
  • Location
    Eindhoven
  • Pronouns
    he/him
  • Joined

More fromTom Nijhof

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp