Skip to content

Instantly share code, notes, and snippets.

@edersonbadeca
Created October 14, 2024 14:32
Show Gist options
  • Save edersonbadeca/a7af9127f2c535a8de2768420d092c98 to your computer and use it in GitHub Desktop.
Save edersonbadeca/a7af9127f2c535a8de2768420d092c98 to your computer and use it in GitHub Desktop.
Git branches cleaner
#!/bin/bash
EXCEPT_BRANCHES=("main")
usage() {
echo "Usage: $0 --except 'branch1 branch2 ...'"
exit 1
}
while [[ "$#" -gt 0 ]]; do
case $1 in
--except)
if [ -z "$2" ]; then
usage
fi
IFS=' ' read -r -a EXTRA_EXCEPT <<< "$2"
EXCEPT_BRANCHES+=("${EXTRA_EXCEPT[@]}")
shift 2
;;
*)
usage
;;
esac
done
branches=$(git branch --format="%(refname:short)")
echo "The following branches will be deleted:"
for branch in $branches; do
delete=true
for except in "${EXCEPT_BRANCHES[@]}"; do
if [ "$branch" == "$except" ]; then
delete=false
break
fi
done
if [ "$delete" == true ]; then
echo "git branch -D $branch"
else
echo "Skipping branch: $branch"
fi
done
read -p "Do you really want to execute the branch exclusion? (y/n) " confirm
if [[ "$confirm" != "y" ]]; then
echo "Branch deletion canceled."
exit 0
fi
for branch in $branches; do
delete=true
for except in "${EXCEPT_BRANCHES[@]}"; do
if [ "$branch" == "$except" ]; then
delete=false
break
fi
done
if [ "$delete" == true ]; then
git branch -D "$branch"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment