In June 2020, GitHub announced they were working on plans to change the default branch name from ‘master’ to ‘main’. The reasoning was to remove any terminology that is linked in any way to the master/slave metaphor. GitHub made the change that year, and since then other organizations and individuals have been following suit.
To rename just a handful of repositories, using the UI is a great option. If you have multiple repositories that you need to change the default branch name on (or even just want to rename the same-named non-default branch on multiple repositories, using a script can be particularly helpful. Both using the UI and using a script will also ensure open pull requests are re-targeted, draft releases are updated, notices are shown to contributors who git push
to the old branch, and more.
To use a Bash script, you can add the following into a new blank file, save it with a .sh
extension it, and run it (you will need to make it executable first). The following snippet includes two different ways to utilize the GitHub API – CURL or using the GitHub CLI. This first snippet uses CURL:
#!/usr/bin/env bash
set -eo pipefail
BASE=$(cd $(dirname "${BASH_SOURCE[0]}")/.. && pwd)
echo -e "What is your GitHub personal access token? See here for more: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token >"
read -s -r usertoken
REPOSITORIES=(example-repository1 example-repository2 example-repository3)
# For example 'octocat' in this example: https://github.com/octocat/Hello-World
REPOSITORYOWNER = exampleowner
# Renaming the default branch in a list of given repositories, using CURL
for REPOSITORY in "${REPOSITORIES[@]}"; do
echo "Renaming master to main on ${REPOSITORY}"
curl \
-X POST \
-H "Authorization: token ${usertoken}" \
--fail "https://api.github.com/repos/${REPOSITORYOWNER}/${REPOSITORY}/branches/master/rename" \ -d '{"new_name":"main"}'
done
echo "Script execution complete"
In terms of shell scripting best practice, there is a post here that covers in more detail what the first few lines of the script are doing.
This second snippet uses the GitHub CLI and can replace the for loop that uses CURL, above:
# Renaming the default branch in a list of given repositories, using GitHub CLI
for REPOSITORY in "${REPOSITORIES[@]}"; do
echo "Renaming master to main on ${REPOSITORY}"
gh api \
--method POST \
-H "Accept: application/vnd.github.v3+json" \
"/repos/${REPOSITORYOWNER}/${REPOSITORY}/branches/master/rename" \
-f new_name='main'
done
echo "Script execution complete"
Creating the script for this was the first time I worked with Bash scripts, so if you have any scripting tips I’d love to hear them!