Using tags in Git
Tags are a way to give names to a particular commit in Git. As you have seen, commits in Git are identified by the commit hash (the long, hexadecimal sequence) or its abbreviated version (the first 7 chars of the hash). This provides an unique identification for each commit, that you can list with the git log
command:
$ git log
commit 55c6cbf8b62014cf62953401f56d77557706f83e (HEAD, tag: mf_improved)
Author: Pedro Fonseca <pf@ua.pt>
Date: Wed Mar 17 15:55:10 2021 +0000
Use of multiple source files (improved).
The header file is "guarded" with a #ifndef #define ... #endif structure.
commit 773afea8a75f3823071d06b64fda214e1528af00 (tag: mf_ok)
Author: Pedro Fonseca <pf@ua.pt>
Date: Wed Mar 17 15:40:56 2021 +0000
[more lines follow]
To get the abbreviated hash, you can use the --oneline
option in the git log
command:
$ git log --oneline
55c6cbf (HEAD, tag: mf_improved) Use of multiple source files (improved).
773afea (tag: mf_ok) Use of multiple source files ok.
7f55874 (tag: mf_nok) Use of multiple source files.
8dd9395 (tag: simple) Simple "Hello, World!" program
These hash sequences, although unique and useful for a computer to read, are not practical for humans. That’s why Git has tags. Tags allow to add a readable name (or sort of) to a commit. Note that, in the previous examples, all commits have a tag. After a commit has been tagged, the tag name can be used to identify that commit, replacing the hard to remember hash string.
Using the examples above, it is much easier to checkout the commit with a simple “Hello, World” program using the tag. The two following commands are equivalent, but one is simpler to remember:
$ git checkout 8dd9395
$ git checkout simple
Creating tags
To create a tag and associate the tag to a commit, checkout the commit you want to tag and issue the command git tag
:
$ git checkout 8aaa2d2
$ git tag Tag_Name
You can also tag a commit by specifying the hash in the command line. The following line would have a similar effect to the two previous commands (with the difference that no checkout is performed):
$ git tag Tag_Name 8aaa2d2
Tag_Name
will be the name of the tag. It could be v1.4
if you are developing code with version numbering, for instance. You can now use it to checkout that commit:
$ git checkout Tag_Name
Pushing tags to a remote repo
Something to take into consideration when using tags and remote repositories, is that tags are not pushed to the remote repository unless that is explicitly stated. This means that git push
by itself will upload the local changes to the remote repository, but will not upload tags. Tags are uploaded to the remote repository with the option --tags
:
$ git push --tags
So, if you need to store your tags in the remote repository, do not forget to add --tags
to the git push
command.
More info:
Comments
Your comments are welcome. Feel free to leave here your remarks or your opinion!