Last active
January 22, 2024 22:39
-
-
Save ric-evans/fad55f31841f3c041f5678240843b528 to your computer and use it in GitHub Desktop.
Fetch, prune, & delete merged local git branches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -x # turn on debugging | |
set -e # exit on fail | |
######################################################################## | |
# | |
# Fetch, prune, & delete merged local git branches | |
# | |
######################################################################## | |
date | |
pwd | |
root=$(git rev-parse --show-toplevel) | |
here=$(git rev-parse --abbrev-ref HEAD) | |
echo "current branch: $here" | |
trap "cd $root && git checkout $here && git pull" EXIT # always return to original branch | |
DEFAULT_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@') | |
echo "default branch: $DEFAULT_BRANCH" | |
git checkout $DEFAULT_BRANCH | |
echo "---" | |
echo "[fetch + prune remote references]" | |
git fetch -p | |
echo "---" | |
echo "[all branches]" | |
git branch -a | |
echo "---" | |
echo "[local branches]" | |
git branch -vv | |
echo "---" | |
echo "[delete merged local branches]" | |
# git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do | |
# echo "$branch:" | |
# mergeBase=$(git merge-base $DEFAULT_BRANCH $branch) | |
# echo " best common ancestor with $DEFAULT_BRANCH: $mergeBase" | |
# if [[ $(git cherry $DEFAULT_BRANCH $(git commit-tree $(git rev-parse "$branch^{tree}") -p $mergeBase -m _)) == "-"* ]]; then | |
# echo " remote has been merged! deleting $branch" | |
# git branch -D $branch | |
# else | |
# echo " local branch has not been merged into $DEFAULT_BRANCH" | |
# fi | |
# done | |
# https://stackoverflow.com/a/33548037/13156561 | |
for branch in $(git for-each-ref --format '%(refname) %(upstream:track)' refs/heads | awk '$2 == "[gone]" {sub("refs/heads/", "", $1); print $1}'); do | |
# echo $branch | |
git branch -D $branch | |
done | |
echo "---" | |
echo "[local branches]" | |
git checkout $here || true # branch may have been deleted | |
git branch -a | |
git pull |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment