Skip to content

Instantly share code, notes, and snippets.

@radlinskii
Last active April 4, 2022 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save radlinskii/76a648fac7d02bc48b3f09f1c3468bd3 to your computer and use it in GitHub Desktop.
Save radlinskii/76a648fac7d02bc48b3f09f1c3468bd3 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 not delete master
branch_names_to_keep+=("main") # do not 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