Sub topic 5
Tagging an Earlier Commit
This chapter assumes you can make commits and read git log. It also assumes you know the difference between lightweight and annotated tags. Both are covered earlier in this tutorial.
Why tag a past commit
Often you realize only later that a particular commit was the release. Maybe you forgot to tag before moving on, or you are adding tags to a repository that never had any. Git lets you attach a tag to any commit, not only the one you have checked out.
By default, git tag points at HEAD. To tag something else, add a commit reference as the last argument.
Find the commit
Use git log --oneline to list recent commits with short hashes.
# Find the commit you want to tag
git log --oneline
# Tag it by passing its hash (replace 4f2a9c1 with a real hash)
git tag -a v0.9.0 -m "Beta release" 4f2a9c1The hash can be abbreviated, as long as it is unique in the repository. Any reference that resolves to a commit also works, such as HEAD~3 or a branch name.
Check the result
Run git show on the new tag to confirm it points where you expect.
git show v0.9.0For an annotated tag, the output starts with the tagger, date and message. The commit it points to follows. The tag's date is when you created the tag. The commit keeps its own, older date. This is correct, and it is useful when you want to know when a tag was added.
The tag stays on commit B while main moves forward with new commits.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `fatal: tag 'v0.9.0' already exists` | The name is already used | Pick a new name, or delete the old tag first |
| `fatal: Failed to resolve '4f2a9c1' as a valid ref` | Typo, or the commit is not in this repository | Re-check with `git log --oneline` |
| The tag appears on the wrong commit | You omitted the hash, so Git used `HEAD` | Delete the tag and create it again with the hash |
| Tag is missing on GitHub | Tags are not pushed by default | Push it by name, as described in the next chapter |
Tagging without switching branches
You do not need to check out the old commit. Passing the hash leaves your working directory and current branch untouched. This is safer than a detached HEAD, because you cannot accidentally commit onto the wrong base.
Exercise
Your last commit is a1b2c3d, but the release was three commits earlier at 9e8f7a6. Write the command that creates an annotated tag v2.0.0 with the message "Release 2.0.0" on the earlier commit. What does the tag's date show?
Show answer
git tag -a v2.0.0 -m "Release 2.0.0" 9e8f7a6. The tag's date is the moment you ran the command. The commit it points to keeps its original date.