Skip to content

Instantly share code, notes, and snippets.

@Galeas
Created May 26, 2025 16:19
Show Gist options
  • Select an option

  • Save Galeas/3a859fd700d6f6b716a74167ab705997 to your computer and use it in GitHub Desktop.

Select an option

Save Galeas/3a859fd700d6f6b716a74167ab705997 to your computer and use it in GitHub Desktop.
The script checks for remote-less local branches and prunes it
#!/bin/zsh
# Git branch cleanup script - removes local branches whose remotes were deleted
# Usage: ./git_cleanup.sh [path-to-git-repo]
set -e
# Handle path parameter
if [ $# -gt 1 ]; then
echo "Usage: $0 [path-to-git-repo]"
exit 1
fi
REPO_PATH=${1:-.}
# Change to the specified directory
if [ ! -d "$REPO_PATH" ]; then
echo "❌ Error: Directory '$REPO_PATH' does not exist"
exit 1
fi
cd "$REPO_PATH"
# Check if it's a git repository
if [ ! -d ".git" ] && ! git rev-parse --git-dir > /dev/null 2>&1; then
echo "❌ Error: '$REPO_PATH' is not a git repository"
exit 1
fi
echo "πŸ“ Working in repository: $(pwd)"
echo "πŸ” Checking for branches with deleted remotes..."
# First, prune remote tracking branches
echo "πŸ“‘ Pruning remote tracking branches..."
git remote prune origin
# Get list of local branches that track deleted remotes
GONE_BRANCHES=$(git for-each-ref --format '%(refname:short) %(upstream:track)' refs/heads | awk '$2 == "[gone]" {print $1}')
if [ -z "$GONE_BRANCHES" ]; then
echo "βœ… No branches found with deleted remotes."
exit 0
fi
echo "πŸ—‘οΈ Found branches with deleted remotes:"
echo "$GONE_BRANCHES" | sed 's/^/ - /'
# Ask for confirmation
echo -n "❓ Do you want to delete these branches? (y/N): "
read -r REPLY
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "❌ Cancelled."
exit 0
fi
# Delete the branches
echo "πŸ—‘οΈ Deleting branches..."
echo "$GONE_BRANCHES" | while read -r branch; do
if [ -n "$branch" ]; then
echo " Deleting: $branch"
git branch -D "$branch"
fi
done
echo "βœ… Cleanup complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment