Git 标签常见操作

2025-07-02 18:14:00
丁国栋
原创 10
摘要:本文记录和汇总Git标签的常见操作。

在 Git 中,你可以在指定的 commit 上创建标签(tag)并附带描述信息。标签分为 轻量标签(lightweight)附注标签(annotated),其中 附注标签 可以存储额外的描述信息(如标签作者、日期、说明等)。


1. 创建附注标签(推荐,可带描述)

git tag -a <tag-name> <commit-hash> -m "标签描述信息"

参数说明:

  • -a--annotate:创建附注标签(annotated tag),可以存储额外信息。
  • <tag-name>:标签名称(如 v1.0.0)。
  • <commit-hash>:要打标签的 commit 哈希值(如 a1b2c3d),这个参数可以省略,如果省略则为当前分支最新的commit。
  • -m:添加标签描述信息(类似 git commit -m),这个参数可以省略。

示例:

git tag -a v1.2.0 abc1234 -m "Release version 1.2.0 with new authentication feature"

2. 创建轻量标签(不带描述)

如果不需要额外信息,可以使用轻量标签:

git tag <tag-name> <commit-hash>

示例:

git tag v1.2.0-lightweight abc1234

⚠️ 注意:轻量标签只是一个指向 commit 的引用,不能存储描述信息。


3. 查看标签信息

git show <tag-name>

示例:

git show v1.2.0

输出示例:

tag v1.2.0
Tagger: Your Name <your@email.com>
Date:   Mon Jan 1 12:00:00 2024 +0800
Release version 1.2.0 with new authentication feature
commit abc1234...
Author: Your Name <your@email.com>
Date:   Sun Dec 31 12:00:00 2023 +0800
    Add new authentication feature

4. 推送标签到远程仓库

默认情况下,git push 不会推送标签,需要手动推送:

# 推送单个标签
git push origin <tag-name>
# 推送所有本地标签
git push origin --tags

5. 删除标签

# 删除本地标签
git tag -d <tag-name>
# 删除远程标签
git push origin --delete <tag-name>

总结

操作 命令
创建附注标签(带描述) git tag -a <tag-name> <commit-hash> -m "描述"
创建轻量标签(无描述) git tag <tag-name> <commit-hash>
查看标签信息 git show <tag-name>
推送标签到远程 git push origin <tag-name>git push origin --tags
删除标签 git tag -d <tag-name>(本地)
git push origin --delete <tag-name>(远程)

推荐使用 附注标签(annotated tag),因为它可以存储更丰富的元数据,适合版本发布等重要操作。

发表评论
博客分类