Skip to content

Instantly share code, notes, and snippets.

@digiwombat
Created May 6, 2023 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digiwombat/9ae055d22c81a42c5bfdd2ca18447254 to your computer and use it in GitHub Desktop.
Save digiwombat/9ae055d22c81a42c5bfdd2ca18447254 to your computer and use it in GitHub Desktop.
A bash script which renames branches recursively.
#!/bin/env bash
# This script is public domain.
# If your government doesn't allow that, it doesn't matter. What're they gonna do? Sue me?
# Just a useful script for changing the name of your repo.
# Variables
ROOT_FOLDER=~/
OLD=${1:-main}
NEW=${2:-master}
case $1 in
--help)
# Print a help message and exit
echo "Usage: ./rename_branches.sh [old_branch] [new_branch]"
echo "This script will change the name of all git repos in subfolders of ${ROOT_FOLDER} from old_branch to new_branch."
echo "If no arguments are provided, it will use default values defined in the script."
echo "Use at your own risk!"
exit 0
;;
esac
echo "This script will changes the name of all git repos"
echo "in subfolders of ${ROOT_FOLDER} from '${OLD}' to '${NEW}'!"
echo "Use at your own risk!"
set -e
for FOLDER in $(find ${ROOT_FOLDER} -name ".git" | sed "s/.git$//")
do
echo "${FOLDER}"
# Check if the folder is a valid git repo
if [ -d "${FOLDER}/.git" ]; then
read -rp "Rename ${OLD} to ${NEW}? " yn
case $yn in
[Yy]* )
cd "${FOLDER}"
# Check if the old branch exists
if git show-ref --verify --quiet "refs/heads/${OLD}"; then
git branch -m "${OLD}" "${NEW}"
# Check if the remote origin exists
if git ls-remote --exit-code origin &>/dev/null; then
git push -u origin "${NEW}"
git push origin --delete "${OLD}"
else
echo "Remote origin does not exist."
fi
else
echo "Branch ${OLD} does not exist."
fi
;;
[Nn]* ) echo Skipped repo; continue;;
* ) echo "Please answer yes or no.";;
esac
else
echo "Not a valid git repo."
fi
echo ""
done
echo "Script finished."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment