← Catalog Matrix

Deployment Execution Blueprint

---
title: Ultimate Git Clean Up Script for Stale Local Branches
description: A fast, production-ready Bash script to clean up local Git branches that have already been merged or deleted on your remote repository.
category: DevOps
slug: bash-git-stale-branch-cleaner
keywords: git cleanup local branches, remove stale git branches, git prune origin shell script, automated git housekeeping, terminal optimization boilerplate
---

### Overview & Problem Matrix
When collaborating inside active, agile development teams, you continuously pull, branch, and merge dozens of core features or technical fixes weekly. Over time, your local machine accumulates a massive inventory of stale local tracking branches that were already safely merged and deleted on your remote repository host (such as GitHub, GitLab, or Bitbucket). 

Manually tracking down and running individual deletion commands (`git branch -d`) item-by-item is an incredibly tedious task, and leaving hundreds of dead references active clutters your shell auto-complete terminal workflows. You need a fast, zero-dependency housekeeping automation script that syncs remote pipelines and safely purges dead local entries without altering your active workspace parameters.

### Implementation Guide & Setup Steps
To install and deploy this Git cleaning script globally across your local development computer, complete these administrative steps:

1. Stage Your Housekeeping Script: Save the optimized automated blueprint detailed below inside your local user profile bin folder pathway as `git-clean`:
   $ nano /usr/local/bin/git-clean
   
   # Note: If your system has user execution constraints, you can place 
   # the binary tracking file path layout inside your root environment directory.

2. Elevate File Privileges: Convert your saved script file from a standard text asset into an active, system-executable utility block:
   $ chmod +x /usr/local/bin/git-clean

3. Execute Housekeeping Routines: Navigate into any active Git project directory workspace layout on your machine and fire the custom helper command straight from your command line:
   $ git-clean

#!/bin/bash

# Ensure we are inside a valid git tracking repository framework
if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
    echo "[ERROR] This directory is not a valid Git repository runtime environment."
    exit 1
fi

echo "Fetching latest remote state and pruning stale tracking references..."
git fetch --prune --all

# Set primary trunk branch targets to guard against accidental structural deletion loops
DEFAULT_BRANCHES="^(master|main|development|staging)$"

echo "Scanning for stale tracking references..."

# Loop through local branches that are explicitly flagged as ': gone]' on the remote upstream origin
# Normalization Fix: Cleanly isolate the branch column header text field while bypassing active checkout markers (*)
git branch -vv | grep ': gone]' | sed 's/^[ *]*//' | awk '{print $1}' | while read -r branch; do
    
    clean_branch=$(echo "$branch" | tr -d '*')
    
    if [ -z "$clean_branch" ]; then
        continue
    fi

    # Guard condition: Never drop standard core production or delivery baseline branch paths
    if echo "$clean_branch" | grep -Eq "$DEFAULT_BRANCHES"; then
        echo "[SKIP] Safeguarded branch protected from automated purging: ${clean_branch}"
        continue
    fi

    echo "[PURGING] Removing stale local branch reference: ${clean_branch}..."
    # Safe delete parameter ensures unmerged feature sets are not destructively dropped
    git branch -d "$clean_branch" > /dev/null 2>&1
    
    # If safe delete checks fail due to unmerged structural data fragments, present an alert notice
    if [ $? -ne 0 ]; then
        echo "  [WARNING] Action skipped. '${clean_branch}' contains unmerged work vectors. Use 'git branch -D ${clean_branch}' if safe."
    fi
done

echo "Git branch cleanup operational sequence completed."