Skip to content

Instantly share code, notes, and snippets.

@AlexeySetevoi
Created July 23, 2025 14:12
Show Gist options
  • Save AlexeySetevoi/5272558cd1af551dd09ec2f18b543dea to your computer and use it in GitHub Desktop.
Save AlexeySetevoi/5272558cd1af551dd09ec2f18b543dea to your computer and use it in GitHub Desktop.
Removes local branches that no longer exist on origin
#!/bin/bash
echo "Fetching latest information from origin..."
git fetch origin --prune
echo ""
echo "Identifying local branches that no longer exist on origin..."
# Get a list of local branches
LOCAL_BRANCHES=$(git branch --list | sed 's/\* //g' | sed 's/ //g')
# Get a list of remote branches from origin
REMOTE_BRANCHES=$(git branch -r | grep origin/ | sed 's/origin\///g' | sed 's/ //g')
BRANCHES_TO_DELETE=()
for local_branch in $LOCAL_BRANCHES; do
# Skip master/main and other protected branches if you have them
if [[ "$local_branch" == "master" || "$local_branch" == "main" ]]; then
continue
fi
# Check if the local branch exists on origin
echo "$REMOTE_BRANCHES" | grep -q "^$local_branch$"
if [ $? -ne 0 ]; then
# Branch does not exist on origin
BRANCHES_TO_DELETE+=("$local_branch")
fi
done
if [ ${#BRANCHES_TO_DELETE[@]} -eq 0 ]; then
echo "No local branches found that are not on origin. Your local repository is clean!"
else
echo ""
echo "The following local branches appear to no longer exist on origin:"
for branch in "${BRANCHES_TO_DELETE[@]}"; do
echo "- $branch"
done
echo ""
read -p "Do you want to delete these branches? (y/N): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
for branch in "${BRANCHES_TO_DELETE[@]}"; do
echo "Deleting branch: $branch..."
git branch -D "$branch"
done
echo "Done! Local branches have been cleaned up."
else
echo "No branches were deleted."
fi
fi
echo ""
echo "Script finished."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment