Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A bash script to interactively remove local and remote git branches
#!/usr/bin/env bash
# A bash script to clean up local and remote git branches. Source it from your
# .bash_profile and you'll get several functions
# delete_branches: Iterates through your local branches and attempts to delete locally
# and pushed. Pass the -r flag to itereate through all remote branches
# and delete local and pushed.
# delete_branch: Attempts to delete a specific named branch locally and pushed.
# With great power comes great responsiblity. Don't delete branches that aren't yours without
# first assuring they are not needed anymore. There are some built-in safeguards:
# 1. The current branch will be ignored, as well as any branch with the dev, prod, master, qa or staging
# substrings.
# 2. When calling delete_branches, you will be prompted for confirmation for every deletion.
function get_branches {
# Skip current branch, or any branch deemed permenent.
if [ $1 = true ]; then
branches=$(git branch -r)
branches=$(git branch)
echo "$branches" | grep -Ev '(^\*|dev|prod|master|qa|staging)'
function delete_local_branch {
# Remove /origin from remote name
b=$(echo $1 | sed "s:origin/::")
# In case branch doesn't exist locally, ignore error
git branch -D $b
function delete_remote_branch {
# Remove /origin from remote name
b=$(echo $1 | sed "s:origin/::")
# In case branch doesn't exist remotely, ignore error
git push origin --delete $b
function delete_branch {
delete_local_branch $1
delete_remote_branch $1
function delete_branches {
# For now if first arg is -r, query
# remote branches.
git fetch
git remote prune origin
if [ "-r" == "$1" ]; then
while read -r line; do
echo "Do you really want to delete the branch '$line' (y/n)?"
read answer </dev/tty
if [ "$answer" != "${answer#[Yy]}" ] ;then
delete_branch $line
echo "'$line' branch not deleted"
done <<< "$(get_branches $remote)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.