Skip to content

Instantly share code, notes, and snippets.

@L1ghtmann
Created August 23, 2023 23:15
Show Gist options
  • Select an option

  • Save L1ghtmann/20f30c29c7371497c6276b24e034d0cb to your computer and use it in GitHub Desktop.

Select an option

Save L1ghtmann/20f30c29c7371497c6276b24e034d0cb to your computer and use it in GitHub Desktop.
Deletes local git repos with no remote equivalent (i.e., branches deleted remotely)
#!/usr/bin/env bash
set -e
# Accept 'D' flag
while getopts ":D:" flag; do
case "$flag" in
# Assign the arg associated with -D to $directory
D) directory="$OPTARG" ;;
*) echo "$0: Option -$OPTARG requires an argument." 1>&2
exit 1
;;
esac
done
# Check that all arguments were passed
if [[ -z $directory ]]; then
echo "Usage: $0 -D path" >&2
exit 0
fi
if [[ -z $(command -v git) ]]; then
echo "Please install git."
exit 0
elif ! [[ $(cd $directory && git rev-parse --is-inside-work-tree 2> /dev/null) == "true" ]]; then
echo "Please ensure $directory is a git repo."
exit 0
fi
# get local branches, excluding HEAD
readarray -t local <<< $(git branch | grep -v "*" | sed -e 's/^[[:space:]]*//')
for i in "${local[@]}"; do
# if no remote, will be blank
if [[ -z $(git branch -r --contains "$i") ]]; then
echo "Local branch '$i' has no remote equivalent. Deleting."
git branch -D $i \
&& echo "Success!" \
|| (echo "Failure!"; exit 1)
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment