How to Tag an Older Commit in Git

John Wachira Feb 15, 2024
How to Tag an Older Commit in Git

This article outlines the steps needed to tag an older commit in Git. We use git tags to mark specific points in our commit history as significant.

Usually, a git tag will mark a stable release or an important milestone in a project. How do you tag an arbitrary git commit?

Tag an Older Commit in Git

For easier context, we will use a hypothetical situation.

Let’s say we have our production code in a Git repository. Since the start of the project, we have made several commits to our repository.

We want to tag the first commit in our repository and mark it as the latest stable version of our code. How do we go about this?

Assuming the image below represents our commit history, how do we tag the first commit?

commit history

To tag a commit, we use the git tag command with the -a option. We will also have to pass the SHA-1 of the commit we want to tag.

In our case, we will run:

$ git tag -a v1.0 9d0a878 -m "Stable"

We use the -m flag to pass a message to our tag. We can push the tag to the remote repository, as illustrated below.

$ git push --tags

The method above will create a tag with the current date and time. If you want to create a tag with the date and time of the commit, follow these steps.

We first need to move HEAD to the commit we want to tag. We will use the git checkout command, as illustrated below.

$ git checkout 9d0a878

To get the date and time of the current commit, we will run:

$ git show --format=%aD  | head -1
Mon, 8 Aug 2022 14:30:26 +0300

To tag our commit with the date and time of the commit, we will run:

$ GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" \
>  git tag -a v1.0 -m"Stable"

We can then push the tag to remote.

$ git push --tags

Our tag should have the date and time of the commit. Let’s confirm our case on GitHub.

our git tag

In a nutshell, you can tag an arbitrary commit in Git. We have discussed how you can tag an older commit with and without the date and time of the commit.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Tag