Introduction
Git tags help developers create source points during development. The primary purpose is to mark and reference release versions. Checkout works with any Git object, including tags.
This tutorial will show you how to check out a Git tag correctly.
Prerequisites
- Git installed and configured.
- A cloned Git remote or a locally set up project.
- Access to the command line/terminal.
Note: Need to install Git? We have guides available for the following OSes:
Git Checkout Tag
To find the tag name and checkout a Git tag, follow the steps below:
1. List the fetched tag names from a remote repository with:
git tag
Alternatively, search the tag names by a specified pattern:
git tag -l "<pattern>"
For example:
git tag -l "v2.*"
Proceed to the final step once you’ve found the tag name you’d like to checkout.
2. Checkout the tag with:
git checkout <tag name>
For example:
git checkout v2.1
The command makes the repository go into Detached HEAD state.
The state allows viewing, making changes, and committing. However, no specific branch is tracking these changes. To confirm this, run the following command:
git branch
The output shows the commits currently associated with a specific revision instead of a branch.
Checkout Git Tag as a Branch
To checkout a Git tag as a branch, create a new branch and add a tag name:
git checkout -b <new branch name> <tag name>
For example, to check out a v2.1
tag to a version2.1
branch, use:
git checkout -b version2.1 v2.1
The output confirms the branch switch.
Print the logs to the console to verify the code starts from the tag:
git log --oneline --graph
Press q to exit the log. To push the changes from the local branch, set an upstream branch and push the code.
How to Checkout the Latest Git Tag
Follow the steps below to check out the latest Git tag:
1. Fetch the latest tags from the repository:
git fetch --tags
The command retrieved one new tag from the remote repository.
2. Use the git describe
command to fetch the latest tag with commits and save the information into the $tag
shell variable:
tag=$(git describe --tags `git rev-list --tags --max-count=1`)
Use the echo command to show the tag name. The variable stores the tag with the latest commit from all branches.
3. Lastly, checkout the tag to a new branch with:
git checkout $tag -b latest
The branch latest
now tracks the changes made starting from the latest tag.
Conclusion
After this tutorial, you know how to check out a Git tag in a detached head state and a new branch. The tags help track release version information.
Next, grab our Git commands cheat sheet PDF with commonly used Git commands.
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/222561.html