Skip to content

Instantly share code, notes, and snippets.

@GrayedFox
Last active April 26, 2024 08:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save GrayedFox/8250e7a49bfffdb581f6356a43188de2 to your computer and use it in GitHub Desktop.
Save GrayedFox/8250e7a49bfffdb581f6356a43188de2 to your computer and use it in GitHub Desktop.
Remove local branches with a missing (gone) upstream
#!/usr/bin/env bash
# first we prune origin to ensure our local list of remote branches is up to date
git remote prune origin
GONE_BRANCHES=$(git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}')
if [ -z "$GONE_BRANCHES" ]; then
echo "Could not find any local branches that have a gone remote"
exit 0
fi
if [ "$1" = "-f" ]; then
echo "$GONE_BRANCHES" | xargs git branch -D
else
echo "$GONE_BRANCHES" | xargs git branch -d 2>/dev/null
if [ $? -ne 0 ]; then
FAILED_TO_DELETE="true"
fi
fi
if [ "$FAILED_TO_DELETE" = "true" ]; then
echo "error: Some local branches are not fully merged."
echo "If you are sure you want to delete them, run 'git-glean -f'"
fi
# Handy script when following GitFlow and rebasing, since `git branch --merged main` will never list
# a rebased but merged branch (as their commit history differs).
@GrayedFox
Copy link
Author

Updated to consume default git error message and output helpful error text

@GrayedFox
Copy link
Author

Updated to prune remote branches before attempting glean

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment