Skip to content

Instantly share code, notes, and snippets.

@douglascayers
Last active September 6, 2023 14:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save douglascayers/661eef9ff9f45a49b2025f6cbdc5679e to your computer and use it in GitHub Desktop.
Save douglascayers/661eef9ff9f45a49b2025f6cbdc5679e to your computer and use it in GitHub Desktop.
Delete local branches that no longer exist on a remote
#!/bin/bash
set -e
# Delete all local branches whose remote branch no longer exists.
git branch -v | grep -E "[0-9a-zA-Z]{7} \[gone\]" | awk '{ print $1 }' | xargs git branch -D $1
# The commmand explained:
#
# List all branches. The -v flag will include "[gone]" in the output if the remote tracked branch no longer exists.
# git branch -v
#
# Next filter rows that indicate their remote tracked branch no longer exists.
# The regex matches on the commit hash then the phrase "[gone]".
# grep -E "[0-9a-zA-Z]{7} \[gone\]"
#
# For each matched row, pull the first column, which is the local branch name.
# awk '{ print $1 }'
#
# Lastly, pass each branch name to the git branch delete command.
# xargs git branch -D $1
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment