Skip to content

Instantly share code, notes, and snippets.

@krshnpatel
Last active November 7, 2022 13:05
Show Gist options
  • Save krshnpatel/a214f67f6d4411d7b93c6d87ce9bf7e2 to your computer and use it in GitHub Desktop.
Save krshnpatel/a214f67f6d4411d7b93c6d87ce9bf7e2 to your computer and use it in GitHub Desktop.
A simple script to help you sync your local branches with your remote branches.

Overview

Description

This script allows you to sync your local branches with your remote branches. It would detect any local branches that have been deleted on your remote repository. Any local branches that have not been pushed to remote will not be detected because they might be your "work in progress" branches.

NOTE: If you create a local branch, then push it to your remote repository, then you manually delete that branch on your remote repository. This script will detect that local branch. So I would suggest reading the list of branches marked for deletion before allowing this script to delete them.

Purpose

Usually it's a good practice to delete your remote branch after it has been merged to your default branch (i.e. main, master). However, this means that there will be several stale local branches and these will accumulate over time. Essentially, this script will help you delete those stale local branches which have been deleted on the remote repository.

Usage

NOTE: For Windows, use a bash terminal (i.e. install git bash).

Download the script:

$ curl -L https://gist.githubusercontent.com/krshnpatel/a214f67f6d4411d7b93c6d87ce9bf7e2/raw/git-sync-local-branches.sh -O && chmod +x ./git-sync-local-branches.sh

Move the script to a folder that is inside the $PATH environment variable. Then, add this script to your aliases using the following command:

$ git config --global alias.sync-local-branches '!bash git-sync-local-branches.sh'

Go to your local git repository and switch to your default branch (i.e. main, master) then run the alias git command:

$ git sync-local-branches

Demo

demo

#!/bin/bash
cd "$PWD"
run() {
echo "Running git remote prune origin..."
git remote prune origin
echo "Finished running git remote prune origin"
echo
branchesToDelete=($(git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}'))
numOfBranches=${#branchesToDelete[@]}
if [ "$numOfBranches" = "0" ]
then
echo "No local branches to delete."
return
else
echo "Local branches to delete:"
for i in "${branchesToDelete[@]}"; do echo "-> $i" ; done
echo "Total: ${numOfBranches}"
fi
echo
echo -n "Do you want to delete the listed local branches [y/N]: " ; read val
if [ "$val" = "y" ] || [ "$val" = "Y" ]
then
echo
echo "Deleting local branches..."
for i in "${branchesToDelete[@]}"; do git branch -D $i ; done
echo "Local branches deleted."
else
echo
echo "No local branches deleted."
fi
}
run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment