remove unused git branches with one command
Usage | Installation | Annotated source | License
Simply launch the following command in a git repo
cleanup_git_branches
Both zsh and bash shell are supported.
Just copy and paste the cleanup_git_branches
function below in your shell profile or (assuming you are using zsh) do something like
mkdir -p ~/.shell
cd ~/.shell
git clone https://github.com/fibo/cleanup_git_branches.git
echo "source ~/.shell/cleanup_git_branches/fun.sh" >> ~/.zshrc
With the setup above, to update run the following
cd ~/.shell/cleanup_git_branches
git pull origin main
source ~/.zshrc
cd -
To generate sources, enter this repo folder and run make
.
Create a cleanup_git_branches
function
cleanup_git_branches() {
Get current working branch and repo default branch.
WORKING_BRANCH=`git rev-parse --abbrev-ref HEAD`
DEFAULT_BRANCH=`basename $(git symbolic-ref refs/remotes/origin/HEAD)`
Go to default branch.
if [ "$DEFAULT_BRANCH" != "$WORKING_BRANCH" ]; then
git switch $DEFAULT_BRANCH
fi
Remove local branches (excluding main branch) that are already merged.
git branch --merged | grep -v $DEFAULT_BRANCH | while read branch
do
git branch -d $branch
done
Remove local branches with no remote reference.
git fetch -p
for BRANCH_NAME in $(git branch -v | grep '\[gone\]' | awk '{print $1}')
do
git branch -D $BRANCH_NAME
done
Back to previous branch.
if [ "$DEFAULT_BRANCH" != "$WORKING_BRANCH" ]; then
git switch $WORKING_BRANCH
fi
}
If you need to change default branch, once done remotely (for instance on GitHub), you need
to update your local repository.
Assuming the new default branch is main
, launch
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main