Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save voidp34r/8693fbdd2e3fe92dbf0f41637215ed51 to your computer and use it in GitHub Desktop.

Select an option

Save voidp34r/8693fbdd2e3fe92dbf0f41637215ed51 to your computer and use it in GitHub Desktop.
Delete all the git branches but "master", "main", current branch, and every branch name you provide as argument.
#!/bin/sh
function git_branch_delete_all_but() {
branch_names_to_keep=("$@")
branch_names_to_keep+=("master") # do no delete master
branch_names_to_keep+=("main") # do no delete main
branch_names_to_keep+=$(git symbolic-ref --short -q HEAD) # do not delete current branch
branch_names_to_delete=()
for branch_name in $(git for-each-ref --format='%(refname:short)' refs/heads/); do
if [[ ! " ${branch_names_to_keep[*]} " =~ " ${branch_name} " ]]; then
branch_names_to_delete+=$branch_name
fi
done
for branchName in "${branch_names_to_delete[@]}"
do
git branch -D $branchName
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment