20
loading...
This website collects cookies to deliver better user experience
git fetch --prune
to remove the remote-tracking branches that no longer exist on the remote. However, the local branches that track on them still exist. This post aims to tell you how to remove them using the git alias git cleanup
and explain how it works.git-cleanup
under your PATHgit-cleanup
:#!/bin/bash
git fetch --prune && git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -D
Note: The first line(shebang) should be either #!/bin/bash
or #!/bin/zsh
chmod +x ./git-cleanup
git config alias.cleanup "!git-cleanup"
git cleanup
directly in your command line!git-cleanup
. Assume that we have the following branches in the local:main -> origin/main
branch1 -> origin/branch1
branch3
Note: ->
means track on
origin/main
origin/branch2
branch1
is merged and has been removed in the remote. And the branch3
is still under development and hasn't been pushed to remote yet.awk
is a program that helps you parse your stdin. In this case the stdin is the result of git branch -r
:origin/HEAD -> origin/main
origin/main
origin/branch2
origin/HEAD
origin/main
origin/branch2
git branch -vv | grep origin
first.git branch -vv
shows the local branches with their tracking branches in the following:main <SHA> [origin/main] last commit message
branch1 <SHA> [origin/branch1] last commit message
branch3 <SHA> last commit message
grep
to filter the lines with origin
, which means it has a remote-tracking branch. So the output of git branch -vv | grep origin
will be:main <SHA> [origin/main] last commit message
branch1 <SHA> [origin/branch1] last commit message
git branch -r
and git branch -vv | grep origin
to find the local branches which remote-tracking branch has been removed. We are using egrep
with -v
options to select the lines which is not in the git branch -r
. We use -f
option because <()
, which we call Process Substitution, will be treat as a file. /dev/fd/0
means stdin, which is git branch -r
in our case.branch1 <SHA> [origin/branch1] last commit message
awk
to parse the stdin. The result should be:branch1
xargs
works like:for line in stdin
git branch -D line
-D
to force delete even though the branch isn't fully merged. If you don't want to delete the branches that aren't fully merged, please use -d
sh
. So if not specifying this, the script may be triggered by sh
and throws error because sh
doesn't recognize <()
.