#!/bin/bash # This script deletes local branches that have been squash-merged to the main branch # Inspiration: https://github.com/not-an-aardvark/git-delete-squashed # # Usage: git-delete-squashed [remote] # sometimes people use 'upstream' remote=${1:-origin} # could be master or main, depending on local political opinion advances main_branch=$(git symbolic-ref refs/remotes/$remote/HEAD | xargs basename) # get all local branches, these are the candidates to delete git for-each-ref refs/heads/ '--format=%(refname:short)' | while read -r branch; do # find the common ancestor ancestor=$(git merge-base $branch $main_branch) # get the tree for the common ancestor tree_id=$(git rev-parse $branch^{tree}) # generate a commit commit_tree=$(git commit-tree $tree_id -p $ancestor -m "delete branch $branch") # find if the commit is applied to main cherry=$(git cherry $main_branch $commit_tree) # cherry starts with - if it is already applied to main if [[ $cherry == -* ]]; then # delete the branch and print it to the user (set -x; git branch -D $branch) fi done