[TOC] #### 1. 標簽介紹 --- **應用場景** 當我們發(fā)布版本時,通常會先在版本庫打一個標簽,這個標簽就是我們平時所說代碼倉庫的版本號 標簽是版本庫的一個快照,但它其實就是指向某個 commit 的指針。所以,創(chuàng)建和刪除標簽都是瞬間完成的 **git 有 commit ,為什么還要引入 tag ?** “請把上周一的那個版本打包發(fā)布,commit號是 6a5819e...” “一串亂七八糟的數(shù)字不好找!” 如果換一個辦法: “請把上周一的那個版本打包發(fā)布,版本號是v1.2” “好的,按照tag v1.2查找commit就行!” 所以,tag 就是一個讓人容易記住的有意義的名字,它跟某個 commit 綁在一起。 #### 2. 查看標簽 --- ``` # 查看本地庫標簽 git tag # 一行顯示多個標簽 git tag --column ``` #### 3. 創(chuàng)建標簽 --- 創(chuàng)建標簽 ``` # 基于當前 commit id 創(chuàng)建標簽 git tag <tagname> # 基于指定 commit id 創(chuàng)建標簽 git tag <tagname> <commit id> ``` 創(chuàng)建標簽并且添加標簽描述(如果不帶 -m 參數(shù)會進入 vi 編輯模式輸入標簽描述) ``` # `-a, --annotate` 標簽名 `-m, --message` 標簽描述 git tag -a <tagname> -m <message> # 經(jīng)測試,-a 不寫也是可以的 git tag <tagname> -m <message> ``` 使用示例 ``` # 添加標簽 git tag v1.0.0 # 創(chuàng)建標簽并設置標簽描述 git tag v1.0.0 -m '正式上線' git tag -a v1.0.0 -m '正式上線' ``` 當在代碼托管平臺中新增了標簽,如果想要將遠程倉庫中新增的標簽更新到本地,只需執(zhí)行 ``` git pull ``` #### 4. 刪除標簽 --- 有時會因為手速過快導致標簽名稱打錯了,此時可以刪除該標簽,重新創(chuàng)建 因為創(chuàng)建的標簽都只存儲在本地,不會自動推送到遠程庫。所以,打錯的標簽可以在本地安全刪除 ``` # 刪除本地標簽 git tag -d <tagname> # 刪除遠程倉庫中的標簽的幾種方式 git push origin -d <tagname> git push origin :<tagname> git push origin :refs/tags/<tagname> # 使用示例 git tag -d v1.0.0 git push origin -d v1.0.0 git push origin :v1.0.0 git push origin :refs/tags/v1.0.0 ``` 要看看是否真的從遠程庫刪除了標簽,可以登錄遠程倉庫查看,比如: Gitee、GitHub。也可以通過下面命令查看: ``` # 查看遠程庫標簽 git ls-remote --tags ``` #### 5. 修改標簽 --- git 并沒有直接修改標簽名的命令,但是可以根據(jù)標簽名創(chuàng)建新的標簽,然后將舊的標簽刪除 ``` # 根據(jù)指定標簽創(chuàng)建新標簽 git tag <new_tagname> <old_tagname> # 刪除本地倉庫中的舊標簽 git tag -d <old_tagname> # 將新標簽推送到遠程庫、將舊標簽從遠程庫中刪除 git push <remote> <new_tagname> :<old_tagname> ``` 下面兩種寫法等同,建議使用第一種寫法: ``` # 寫法一: # 將新標簽推送到遠程庫、將舊標簽從遠程庫中刪除 git push <remote> <new_tagname> :<old_tagname> # 寫法二: # 將新標簽推送遠程庫 git push <remote> <new_tagname> # 刪除遠程倉庫中的舊標簽 git push <remote> :<old_tagname> ``` #### 6. 推送標簽 --- 將本地標簽推送到遠程倉庫 ``` # 將指定標簽推送到遠程倉庫 git push <remote> <tagname> # 將所有本地標簽一次性推送到遠程倉庫 git push <remote> --tags # 使用示例 git push origin v1.0.0 git push origin --tags ``` #### 7. 檢出標簽 --- 可以通過標簽名稱,檢出相應版本的代碼 ``` git checkout <tagname> ``` 實際開發(fā)中,如果需要基于指定標簽進行開發(fā),可以先檢出標簽,然后創(chuàng)建新的分支,在這個新分支上進行開發(fā) ``` # 切換到標簽對應的提交記錄 git checkout <tagname> # 創(chuàng)建并切換到新分支 git checkout -b <branch> ``` 基于指定標簽創(chuàng)建分支也有更簡潔的寫法 ``` git checkout -b <branch> <tagname> ``` #### 8. git show 查看標簽 --- 查看標簽以及指向的對象。其實就是查看標簽的備注和對應的提交記錄 ``` git show v1.0.0 ``` 查看標簽指向的樹。其實就是查看標簽下的文件 ``` git show v1.0.0^{tree} ``` 查看標簽對應提交記錄的備注信息 ``` git show -s --format=%s v1.0.0^{commit} ```