Remove unused git branches
Simply launch the following command in a git repo
git cleanBranchesGit recognizes any executables in your path that are named git-* as git commands. So to install:
- get the git-cleanBranches file
- make it executable
- add it to your
$PATH
So for example, you can do something like
mkdir -p ~/.shell
cd ~/.shell
git clone https://github.com/fibo/git_cleanBranches.git
echo 'export PATH="$HOME/.shell/git_cleanBranches:$PATH"' >> $HOME/.zprofileWith the setup above, to update run the following
cd ~/.shell/git_cleanBranches
git pull origin main --rebaseTo generate sources, enter this repo folder and run make.
#!/bin/sh
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. Branches checked out in a worktree are kept.
git branch --format='%(refname:short) %(worktreepath)' --merged | while read BRANCH_NAME WORKTREE_PATH
do
if [ -z "$WORKTREE_PATH" ]; then
git branch -d $BRANCH_NAME
elif [ "$BRANCH_NAME" != "$DEFAULT_BRANCH" ]; then
echo "worktree $BRANCH_NAME"
fi
done
Remove local branches and worktrees which remote reference does not exist anymore.
git fetch --prune
for BRANCH_REF in $(git branch -v | grep '\[gone\]' | grep '^+' | awk '{print $3}')
do
git worktree remove `git worktree list | grep $BRANCH_REF | awk '{print $1}'`
done
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