Reputation: 99
I was looking to clear all unused branches from my git repository. There are around 100 branches.
There is a way to select branches one by one from the BitBucket account and delete it manually. But that approach takes along.
So I have created a script that deletes branches in bulk and supported in Linux/Ubuntu.
Create delete_branch.sh
#!/bin/bash
delete_branch(){
BRANCH=$1;
DIR_PATH=<path of your project root>;
cd ${DIR_PATH}
echo git push origin --delete ${BRANCH}
git push origin --delete ${BRANCH}
}
BRANCHES=( branch1 branch2 branch3 ... branchN );
for i in "${BRANCHES[@]}"
do
:
delete_branch $i;
echo deleting branch ${i};
done
execute this file from terminal by ./delete_branch.sh
Upvotes: 1
Views: 611
Reputation: 3238
For me, 'unused' branches are defined as anything merged into the current branch, that is not called master, develop, or release/*. If you agree, you can use these two bash scripts (put them in PATH, the one calls the other).
The default remote to cleanup is called origin, but this can be specified as the second parameter, and the excluded branches are the third parameter.
#!/bin/bash
set -e
function listbranches {
git branch -r --merged | tr -d ' ' | sed "s/$remote\///" | grep -vxE "$excludes"
}
remote=${2:-origin}
excludes=${3:-master|develop|release/.*}
if [ "$1" == "--dry-run" ]; then
echo "The following branches would be deleted:"
listbranches
exit 0;
elif [ "$1" == "--really-delete" ]; then
echo "Deleting remote branches..."
else
echo "Error: first parameter must be either --dry-run or --really-delete"
exit 1
fi
listbranches | deleteremotebranches.sh $remote
#!/bin/bash
set -e
remote=${1:-origin}
xargs git push $remote --delete
Typical usage is to just run cleanupremote.sh
to see the switches required, then repeat it with --dry-run, adding to the third parameter until there are no unwanted branches listed:
cleanupremote.sh --dry-run origin 'master|develop|feature/oh_not_that_one_I_need_it'
cleanupremote.sh --really-delete origin 'master|develop|feature/oh_not_that_one_I_need_it'
It is two seperate files so that you could call deletebranches.sh directly, specifying a remote and piping in the branchnames to delete.
Upvotes: 1