Skip to content

Instantly share code, notes, and snippets.

@ryosms
Last active July 1, 2025 03:27
Show Gist options
  • Select an option

  • Save ryosms/f5bf46808971c0003d411c6c3dac6090 to your computer and use it in GitHub Desktop.

Select an option

Save ryosms/f5bf46808971c0003d411c6c3dac6090 to your computer and use it in GitHub Desktop.

git clean_branch

  1. download the git-clean_branch and place it in a directory included in your PATH
  2. (optional) set your default branch name to environment variable GIT_DEFAULT_BRANCH
    • when each repository has a different default branch, it might be convenient to use direnv
  3. (optional) set alias ex. git config alias.cb "clean_branch"
  4. use git clean_branch
# Copyright (c) 2025 ryosms <[email protected]>
# Licensed under the MIT License. See https://choosealicense.com/licenses/mit/ for details.
set -e
default_branch=${GIT_DEFAULT_BRANCH:-develop}
exclude_branches='(develop|accept|production|master|main)'
debug=""
usage() {
echo "
Cleaning merged branches
usage: git clean_branch [-b <branch_name>] [-e <regex_pattern>] [-v]
-b, --default_branch set default_branch
-e, --exclude_branches branches to exclude from deletion egrep-style <regex_pattern>
-v, --verbose verbose log
-h, --help show this help
" >&2
}
while [[ $# -gt 0 ]]; do
case $1 in
-b|--default_branch) default_branch="${2}"; shift; shift;;
-e|--exclude_branches) exclude_branches="${2}"; shift; shift;;
-v|--verbose) debug="1"; shift;;
-h|--help) usage; exit 1;;
esac
done
if [ "${debug}" == "1" ]; then
echo "default_branch=${default_branch}"
echo "exclude_branches=${exclude_branches}"
set -x
fi
git switch "${default_branch}"
git pull --prune
git branch --merged \
| grep -v '*' \
| egrep -v ${exclude_branches} \
| xargs -n1 git branch -d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment