Skip to content

Instantly share code, notes, and snippets.

@dglazkov
Created September 7, 2025 02:36
Show Gist options
  • Select an option

  • Save dglazkov/196a7167a6f4ad96c25cf71387a282a8 to your computer and use it in GitHub Desktop.

Select an option

Save dglazkov/196a7167a6f4ad96c25cf71387a282a8 to your computer and use it in GitHub Desktop.
Shell script to identify and list local Git branches merged upstream that can be deleted.
#!/bin/bash
# Update remote tracking branches
git fetch --prune
# Get the default branch name (e.g., main or master) from origin
DEFAULT_BRANCH=$(git remote show origin | grep 'HEAD branch' | awk '{print $NF}')
# Fallback if default branch cannot be determined
if [ -z "$DEFAULT_BRANCH" ]; then
echo "Warning: Could not determine the default branch for 'origin'. Assuming 'main'."
DEFAULT_BRANCH="main"
fi
echo "Checking for local branches merged into origin/$DEFAULT_BRANCH that can be deleted:"
echo "--------------------------------------------------------------------------"
# List local branches that are merged into the default remote branch
# Exclude the default branch itself and the currently checked out branch
git branch --merged "origin/$DEFAULT_BRANCH" | \
grep -v "\*" | \
grep -v "$DEFAULT_BRANCH" | \
while read -r branch; do
# Trim whitespace and print
echo " $(echo "$branch" | xargs)"
done
echo "--------------------------------------------------------------------------"
echo "To delete these branches, you can use: git branch -d <branch_name>"
echo "Or for multiple branches: git branch --merged origin/$DEFAULT_BRANCH | grep -v '\*' | grep -v '$DEFAULT_BRANCH' | xargs git branch -d"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment