Skip to content

Instantly share code, notes, and snippets.

@jslay88
Created December 2, 2023 18:06
Show Gist options
  • Save jslay88/2c9df4b99af21a559b73d35e0cdb1d2d to your computer and use it in GitHub Desktop.
Save jslay88/2c9df4b99af21a559b73d35e0cdb1d2d to your computer and use it in GitHub Desktop.
Prune Git Branches
#! /bin/sh
# Pull/Fetch remote branches and prune local branches that have been deleted
# Usage: prune_branches.sh [remote]
# If remote is not specified, it defaults to origin
# If remote is specified, it must be a valid remote name
set -e
# Get the remote name
if [ -z "$1" ]; then
remote="origin"
else
remote="$1"
fi
# Fetch and prune the remote branches
git fetch -p "$remote"
# Get the list of local branches
local_branches=$(git branch | sed 's/^..//')
# echo "Local branches: $local_branches"
# Get the list of remote branches
remote_branches=$(git branch -r | sed 's/^..//' | sed 's/^origin\///')
# echo "Remote branches: $remote_branches"
# Get the list of branches that have been deleted remotely
deleted_branches=$(comm -23 <(echo "$local_branches" | sort) <(echo "$remote_branches" | sort))
# echo "Deleted branches: $deleted_branches"
# Delete the local branches that have been deleted remotely
for branch in $deleted_branches; do
# Skip the current branch
if [ "$branch" = "$(git rev-parse --abbrev-ref HEAD)" ]; then
continue
fi
# Properly quote the branch variable
if ! git branch -d "$branch"; then
# If the branch is not merged, ask the user if they want to delete it
echo "The branch $branch is not merged. Do you want to delete it? [y/N]"
read -r answer
if [ "$answer" != "y" ] && [ "$answer" != "Y" ]; then
continue
fi
# Delete the branch
git branch -D "$branch"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment