Created
May 26, 2025 16:19
-
-
Save Galeas/3a859fd700d6f6b716a74167ab705997 to your computer and use it in GitHub Desktop.
The script checks for remote-less local branches and prunes it
This file contains hidden or 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/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