Skip to content

Instantly share code, notes, and snippets.

@woemar
Created July 13, 2021 19:48
Show Gist options
  • Save woemar/07afd4f7fe3c8037665500c8dbb6e043 to your computer and use it in GitHub Desktop.
Save woemar/07afd4f7fe3c8037665500c8dbb6e043 to your computer and use it in GitHub Desktop.
Bash script to delete branches already merged into master from local and remote repository
#!/bin/bash
###
# This script will remove every branch prefixed feature/, release/ or bugfix/ from your local and the
# remote repository that has already been merged to master.
# Invoke script without params to get an overview of branches to be deleted, supply "--delete" param to
# actually delete the branches.
#
###
function show_merged_branches() {
git branch --list --merged master | gawk '/feature|release|bugfix/ { print $1 }'
}
function cleanup_merged_branches_local() {
git branch --list --merged master | gawk '/feature|release|bugfix/ { print $1 }' | xargs -n1 git branch -d
}
function cleanup_merged_branches_remote() {
git branch --list --merged master --remote | gawk '/feature|release|bugfix/ { print gensub(/\//, " ", "1", $1) }' | xargs -n2 git push --delete
}
if [ "$1" == "--delete" ]; then
echo Cleaning up local branches
cleanup_merged_branches_local >/dev/null 2>&1
echo Cleaning up remote branches
cleanup_merged_branches_remote >/dev/null 2>&1
echo Pruning local repository
git gc --force --prune=all >/dev/null 2>&1
git remote update --prune origin >/dev/null 2>&1
git prune >/dev/null 2>&1
else
show_merged_branches
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment