Skip to content

Instantly share code, notes, and snippets.

@brawlins
Last active May 24, 2024 19:53
Show Gist options
  • Save brawlins/98563783155ac28fe8e317c0a3af26c9 to your computer and use it in GitHub Desktop.
Save brawlins/98563783155ac28fe8e317c0a3af26c9 to your computer and use it in GitHub Desktop.
Shell script that deletes local git branches that were deleted on the remote
#!/bin/zsh
# Deletes local branches that have been deleted on the remote
function pruneLocalBranches {
# Get the main branch name (the one checked out on the remote)
mainBranch=$(git rev-parse --abbrev-ref origin/HEAD | cut -d "/" -f 2)
# Check out that branch because it should never get pruned
git checkout $mainBranch &> /dev/null
# Prune branches
git fetch origin --prune &> /dev/null
# List branches that have been removed from origin and write to file
git branch -vv | awk '/: gone]/{print $1}' > /tmp/branchesToPurge
# Open the file for editing
vim /tmp/branchesToPurge
# Print list of branches to be deleted
echo "The following branches will be deleted:"
cat /tmp/branchesToPurge
# Ask if we should proceed
answer=''
vared -p "Are you sure you want to delete these branches (y/n)? " -c answer
case ${answer:0:1} in
y|Y )
echo "Deleting...";
# Delete branches listed in file
xargs git branch -D < /tmp/branchesToPurge;;
* )
echo "Aborted";;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment