Git - Tagging up commits using Git Tag

This article covers how to use the command 'Git Tag'.

When you've created a new release of your software, you may find that you want use tags.

Tags allow us to mark a commit with a special name, so we can refer to that commit, rather than the whole branch.

Then, if we ever want to get the code for a specific release, we can checkout the tagged commit.

Listing tags

To see all the tags in the repository (ordered alphabetically), we can simply use git tag:

git tag
$ git tag

Sometimes we could have a lot of tags. Fortunately, we can use a pattern to list tags of a certain type:

git tag -l <tag-name-pattern>

For example, if we wanted all tagged releases in v2.20, we could use the * character as follows:

$ git tag -l "v2.20.*"

Creating tags

To create a tag, we only need to include a name:

git tag <tag-name>

For example:

$ git tag v3.0

Creating a tag in this way will create a lightweight tag. This tag is only a name on that branch.

You can also create an annotated tag, using the -a parameter for the name, and -m parameter for an optional message:

git tag -a <tag-name> -m <tag-message>

For example:

$ git tag -a v3.0 -m "New release!"

Using an annotated tag will store more information against the tag, including the creator, a date, and the message.

Tagging a previous commit

If you ever need to add a tag to a previous commit, you can specify the commit ID in the command:

git tag -a <tag-name> <commit-id>

For example:

$ git tag -a v1.0 3573a15a

Pushing tags

Once you've created a tag, you will need to push it to get it on the remote repository.

To do so, you can either push the specific tag, or all tags:

# All tags
git push <remote-name>  --tags

# Specific tag
git push <remote-name> <tag-name>

For example:

# Push all tags to origin
git push origin --tags

# Push the tag "v1.0" to origin
git push origin v1.0

Checkout a tagged commit

You can checkout a tagged branch directly by supplying the tag name to git checkout

git checkout v1.0

However, if your tag is not on the latest commit on that branch, then this will result in a detached HEAD state.

A detached HEAD means that your "HEAD" (i.e. the part that tracks what your current workspace should match) is pointing to a commit, rather than a branch.

In that case, you will get this message:

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

Showing tags

Want to see more information about a tag? You can use git show along with the tag name:

git show <tag-name>

For example:

git show v1.0

Git show tag

Deleting tags

If you ever need to delete a tag, you can use the --delete parameter:

git tag --delete v1.0