Introduction
Git tags are specific reference points in a Git project history. Each tag has a unique name, usually referencing a release version. However, sometimes a Git tag needs to be renamed if the name doesn't follow semantic versioning rules or if the tag name is incorrect.
In this tutorial, you will learn to rename a tag in Git.
Prerequisites
How to Rename a Tag in Git?
Renaming a tag in Git involves creating a new tag and deleting the old one. Renaming a tag in a remote repository requires additional steps compared to renaming a local one. Follow the steps below to rename a Git tag.
Step 1: Create New Tag
Depending on the type of tag you want to rename, create a new lightweight or annotated tag:
Lightweight Tags
Use the following syntax to create a new lightweight tag in place of the old one:
git tag [new_tag_name] [old_tag_name]
For example:
git tag v1.7 v1.6
The command replaces the old lightweight tag (v1.6
) with the new one (v1.7
).
Annotated Tags
The syntax for renaming an annotated tag is:
git tag -a [new_tag] [old_tag]^{} -m [new_message]
For example:
git tag -a v1.7 v1.6^{} -m "Version 1.7 released"
The command replaces the v1.6
tag with v1.7
and adds the new message to the annotated tag.
Note: The above command works for both lightweight and annotated tags. Since annotated tags are objects, the command ensures that the new tag points to the underlying commit and not to the old annotated tag object you want to delete. Lightweight tags aren't considered as objects.
Step 2: Delete the Old Tag
Clean up the local repository by deleting the old tag. If the tag has been pushed to the remote repository, you need to delete the tag from there as well.
Delete Tag in Local Repository
Use the following syntax to delete a tag in the local repository:
git tag -d [old_tag_name]
For example:
git tag -d v1.6
The command removes the old tag from the local repository.
Note: See how to restore a repository if you delete it by mistake.
Delete Tag in Remote Repository
If a tag has been pushed to a remote repository, remove the tag to prevent Git from recreating the old tag when making a pull request.
Use the following syntax to do so:
git push origin [new_tag_name] :[old_tag_name]
For example:
git push origin v1.8 :v1.7
The colon removes the old tag (v1.7
) from the remote repository, replacing it with the new one (v1.8
).
Note: See how to checkout a Git tag to mark and reference release versions properly.
Step 3: Ensure Other Users Clean Their Repository
Your collaborators may still have the old tag in their local repositories. Ensure that they run the following command to clean up their repositories and implement any tag changes you have made:
git pull --prune --tags
Conclusion
This tutorial showed how to rename lightweight and annotated Git tags in a local and remote repository.
For more Git tutorials, see how to work with Git tag releases, checkout Git tags, Git prune command or learn to use Git with our Git beginner's guide.