DEV Community

Cover image for Automating Remote Branch Cleanup in Azure DevOps Using Git and Bash

Automating Remote Branch Cleanup in Azure DevOps Using Git and Bash

Managing remote branches is crucial in keeping a Git repository clean and efficient. Over time, stale branches accumulate, making navigation harder and slowing down repository operations. In Azure DevOps, branches that haven't been used in months can clutter your repository, potentially causing confusion and unnecessary storage costs.

This article presents a Bash script to automate the deletion of remote branches that haven't been modified in over three months. By the end of this guide, you'll have a simple but powerful tool to maintain a clean repository in Azure Repos.

Why Delete Old Remote Branches?

  • Reduce Clutter – Old feature branches make the repository hard to navigate.
  • Improve Performance – Fewer branches mean faster Git operations.
  • Enforce Best Practices – Encourages developers to clean up after merging.
  • Save Storage Space – Reducing unnecessary data stored in Azure DevOps.

The Problem: Stale Branches in Azure DevOps

If you're working on an Azure DevOps repository, you may notice an increasing number of old branches that are no longer relevant. Manually identifying and deleting these branches is tedious, especially in large teams.

The Solution: Automate Cleanup with Bash + Git

  1. 1. We can automate this process by writing a Bash script that:
  2. 2. Fetches all remote branches.
  3. 3. Check the last commit date for each branch.
  4. 4. Deletes branches that haven't been modified in 3+ months.
  5. Asks for confirmation before deleting.

The Bash Script

Below is a fully automated script to clean up remote branches in Azure DevOps repositories:

#!/bin/bash

# Remote repository (default to origin)
REMOTE=${1:-origin}

# Time threshold (3 months ago)
THRESHOLD_DATE=$(date -d "3 months ago" +%s)

# Fetch latest remote branches
git fetch --prune $REMOTE

echo "Checking remote branches older than 3 months..."

# Get remote branches and last commit date
OLD_BRANCHES=()
while read -r branch last_commit_date; do
    # Convert last commit date to Unix timestamp
    LAST_COMMIT_TIMESTAMP=$(date -d "$last_commit_date" +%s)

    # Compare with threshold
    if [[ "$LAST_COMMIT_TIMESTAMP" -lt "$THRESHOLD_DATE" ]]; then
        OLD_BRANCHES+=("$branch")
    fi
done < <(git for-each-ref --format '%(refname:short) %(committerdate:iso8601)' refs/remotes/$REMOTE | sed "s#refs/remotes/$REMOTE/##")

# If no old branches, exit
if [[ ${#OLD_BRANCHES[@]} -eq 0 ]]; then
    echo "No branches older than 3 months found."
    exit 0
fi

# Show branches to be deleted
echo "The following branches are older than 3 months and will be deleted:"
printf '%s\n' "${OLD_BRANCHES[@]}"

# Confirm deletion
read -p "Are you sure you want to delete these branches from Azure DevOps? (y/N): " CONFIRM
if [[ "$CONFIRM" != "y" ]]; then
    echo "Operation aborted."
    exit 0
fi

# Delete branches from Azure DevOps
for branch in "${OLD_BRANCHES[@]}"; do
    echo "Deleting $REMOTE/$branch from Azure DevOps..."
    git push $REMOTE --delete "$branch"
done

echo "Old branches successfully deleted from Azure DevOps."
Enter fullscreen mode Exit fullscreen mode

Key Features

Automatically Detects Old Branches

The script checks when each branch was last modified.

Uses git for-each-ref to get the last commit timestamp.

Compares timestamps to filter branches older than 3 months.

Prevents Accidental Deletion

List branches before deleting them.

Ask for confirmation before proceeding.

Azure DevOps Compatible

Works with Azure Repos (Git) in Azure DevOps.

Uses git push origin --delete to remove branches remotely.

Customizable

Change the time threshold by modifying 3 months ago.

Change REMOTE=${1:-origin} to work with different Git remotes.

πŸ›  How to Use the Script

Save the Script

Create a new file called delete_old_devops_branches.sh and paste the script inside.

Make it Executable

Run the following command:
chmod +x delete_old_devops_branches.sh

Run the Script

Execute the script in your repository:
./delete_old_devops_branches.sh
Or specify a different remote (if not origin):
./delete_old_devops_branches.sh upstream

Enhancing the Script (Optional)

Want to add more features? Here are some ideas:

Exclude Protected Branches (Main, Develop, etc.)

Modify the script to skip the deletion of main, develop, or other critical branches:

EXCLUDED_BRANCHES=("main" "develop" "release")
if [[ " ${EXCLUDED_BRANCHES[@]} " =~ " $branch " ]]; then
    continue
fi
Enter fullscreen mode Exit fullscreen mode

Run in Dry-Run Mode

Instead of deleting, list the branches:
git push --dry-run $REMOTE --delete "$branch"

Schedule Automatic Cleanup

Use cron jobs to run the script monthly:
crontab -e
Add this line:
0 2 1 * * /path/to/delete_old_devops_branches.sh
This will run the script on the 1st of every month at 2 AM.

Final Thoughts

Cleaning up remote branches in Azure DevOps is essential for maintaining a healthy Git repository. By automating this task with a simple Bash script, you save time, improve repository organization, and enforce best practices across your team.

This script is a starting pointβ€”you can extend it further with exclusions, dry-run mode, or automatic scheduling.

πŸ’‘ Have any ideas to improve it? Share your thoughts in the comments!

Top comments (0)