Andy Jarrett // Code. Develop. Create.

Reduce clutter and confusion by finally deleting those old branches, local and remote.

Github dongle, because this post is about Git
Photo by Brina Blum on Unsplash

TL;DR: Jump to the script

I know my way around Git well enough to get by, but recently, I realised just how many old branches we have in our project—some dating back years! It's definitely time for a clean-up. There are plenty of good reasons to do this, like reducing clutter, preventing confusion, improving performance, ensuring security, and freeing up space. So, I decided to tackle the mess. Now, there might be a better way to go about this, but using a script seemed like the most straightforward way to clear out the remote and local branches that are no longer needed.

Deleting Local Branches

For local branches, you can use the following command:

git branch -d [branch name]

This command deletes the branch if it has been fully merged into its upstream branch (usually the branch you're currently on, like main or master).

If the branch has not been merged, you might need to force delete it using:

git branch -D [branch name]

The -D flag is a shorthand for --delete --force, which forcefully deletes the branch, even if it hasn't been merged.

Deleting Remote Branches

For remote branches, use the following command:

git push origin --delete [branch name]

Note that it's --delete, not -d, when deleting remote branches.

That's manageable for a few branches, but if you need a larger cleanup, a script can save a lot of time and effort:

#!/bin/bash

branches=(
  "main_test"
  "main_example"
  "remotes/origin/main_bkp"
  "remotes/origin/main_bkp_bkp"
  "remotes/origin/main_bkp_bkp_20240201"
)

for branch in "${branches[@]}"
do
  # Check if branch is remote or local
  if [[ $branch == remotes/origin/* ]]; then
    remote_branch=${branch#remotes/origin/}
    echo "Deleting remote branch $remote_branch"
    git push origin --delete $remote_branch
  else
    echo "Deleting local branch $branch"
    git branch -D $branch
  fi
done

I’m here, learning and working away. If you liked this content and want to keep me going, consider buying me a coffee. Your support keeps this site running and the coffee brewing! ☕️