Skip to content

Instantly share code, notes, and snippets.

@senorihl
Last active March 31, 2022 07:48
Show Gist options
  • Save senorihl/22ee7018e0c167f994f2e75918de5166 to your computer and use it in GitHub Desktop.
Save senorihl/22ee7018e0c167f994f2e75918de5166 to your computer and use it in GitHub Desktop.
Clean local branches pushed & deleted on remote

Bash script to clean local branches which are pushed & deleted on remote

Installation

wget https://gist.githubusercontent.com/senorihl/22ee7018e0c167f994f2e75918de5166/raw/clean-local-branch.sh -O $HOME/.clean-local-branch.sh
chmod a+x $HOME/.clean-local-branch.sh
git config --global alias.clean-local '!bash $HOME/.clean-local-branch.sh'

Usage

git clean-local [-v|--verbose] [--dry-run]

Description

This command will remove all local branches that does not exists on remotes anymore

Options

  • -h --help Show help screen.
  • -v --verbose Display executed commands.
  • --dry-run Don't execute anything, just simulate commands
#!/usr/bin/env bash
VERBOSE=false
DRY=false
command_help () {
echo ""
echo "Clean local branch."
echo ""
echo -e "\e[33mUsage:\e[0m"
echo " clean-local [-v|--verbose] [--dry-run]"
echo ""
echo -e "\e[33mDescription:\e[0m"
echo " This command will remove all local branches that does not exists on remotes anymore"
echo ""
echo -e "\e[33mOptions:\e[0m"
echo -e " \e[32m-h --help\e[0m Show this screen."
echo -e " \e[32m-v --verbose\e[0m Display executed commands."
echo -e " \e[32m--dry-run\e[0m Don't execute anything, just simulate commands"
echo ""
exit 1
}
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-h|--help)
command_help
shift # past argument
;;
-v|--verbose)
VERBOSE=true
shift # past argument
;;
--dry-run)
DRY=true
shift # past argument
;;
*) # unknown option
shift # past argument
;;
esac
done
die () {
echo >&2 "$@"
exit 1
}
command () {
local __resultvar=$2
[[ "$VERBOSE" = "true" ]] && echo -e "\e[36m$1\e[0m"
if [[ "$DRY" = "false" ]]; then
if [[ "$__resultvar" ]]; then
eval "$__resultvar=\`LC_ALL=C $1\`"
else
eval $1
fi
fi
}
command_no_dry () {
local __resultvar=$2
[[ "$VERBOSE" = "true" ]] && echo -e "\e[36m$1\e[0m"
if [[ "$__resultvar" ]]; then
eval "$__resultvar=\`LC_ALL=C $1\`"
else
eval $1
fi
}
echo -e "Refreshing repository"
command "git fetch -p &> /dev/null"
echo -e "Selecting gone branches"
command "git --no-pager branch -vv | grep \"gone]\" | awk -F' ' '{print \$1}'" gone_branches
gone_branches_list=(`for i in ${gone_branches[@]}; do echo $i; done`)
nb="${#gone_branches_list[@]}"
if [[ "$nb" = "0" ]]; then
echo -e "Nothing to do"
exit 0
fi
echo -e "${#gone_branches_list[@]} branch$([[ "${#gone_branches_list[@]}" -le 1 ]] || echo "es") to delete"
for gone_branch in ${gone_branches_list[@]}
do
echo -e "Deleting branch \e[33m${gone_branch}\e[0m"
command_no_dry "git branch -D ${gone_branch} &> /dev/null"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment