Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rename GIT branches based on a pattern
#!/bin/bash
echo
show_usage() {
cat << EOF
Rename a set of branches, effectively DELETING old
branches and creating new ones based on the old ones.
USAGE
$(basename "$0") <remote> <query>
remote A GIT remote (usually origin)
find A search query to grep for a set of branches
replace Text to replace the find query with
EXAMPLE
$(basename "$0") origin "1.2.2" "1.2.4"
EOF
}
if [[ -z "$1" ]] || [[ -z "$2" ]] || [[ -z "$3" ]]; then
show_usage
exit 1
fi
# Get a list of branches - local only, for now
oldbranches=$(git branch -l | grep "$2")
newbranches=()
echo "Here are the branches and what they will be renamed to."
echo
for branch in $oldbranches; do
echo "$branch"
newbranches+=(${branch/"$2"/"$3"})
echo ${newbranches[${#newbranches[@]} - 1]}
echo
done
# Confirm rename
read -r -p "Are you sure you want to rename these local branches? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
echo "OK"
echo ""
else
echo "Cancelled"
exit 2
fi
# Move (rename) branches
i=0
for oldbranch in $oldbranches; do
git branch -m $oldbranch ${newbranches[$i]}
i=$[i + 1]
done
# Confirm remote delete
read -r -p "Would you like to delete old branches from all remotes? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
echo "OK"
echo ""
else
echo "Cancelled"
exit 2
fi
remotes=$(git remote | cut -f1)
for branch in $oldbranches; do
for remote in $remotes; do
git push $remote :$branch
done
done
echo
# Confirm new push
read -r -p "Would you like to push renamed branches to all remotes? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
echo "OK"
echo ""
else
echo "Cancelled"
exit 2
fi
# Push all new branches
newbranches_len=${#newbranches[@]}
for (( i=0; i < ${newbranches_len}; i++ )); do
for remote in $remotes; do
git push $remote ${newbranches[$i]}
done
done
echo
echo
echo "Finished renaming $newbranches_len branches."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.