Delete local and remote Git tags programmatically

It’s surprising to see how a git repo can become messy as time goes by. Supposedly, you shouldn’t have to do any cleanup since tags are just points in history for your git repository. But what if you do want to delete them? And more, what if you have an awful lot of them and want to delete them programatically? Let’s see how it works.

First things first, make sure you have the same tags locally and on the remote git server:

$ for i in 2013 ; do git tag -l | grep "$i" ; git ls-remote --tags origin | awk '{print ":"$2}' | grep "$i" | grep -v '{}' ; done

2013-01-01
2013-01-01.0
2013-01-04
2013-01-09
(snipped)

:refs/tags/2013-01-01
:refs/tags/2013-01-01.0
:refs/tags/2013-01-04
:refs/tags/2013-01-09
(snipped)

The raw tags are local and the refs/tags/* are being retrieved from the remote. If you do not have the same tags locally and on the remote, start by syncing everything properly in order to prevent issues along the way.

Now that we’ve made sure we can safely wipe everything, let’s do it. Note that in the below example I’m deleting all my tags from 2013. You probably have something different such as a build number or anything so adjust the command accordingly.

$ for i in 2013 ; do git tag -l | grep "$i" | xargs git tag -d ; git ls-remote --tags origin | awk '{print ":"$2}' | grep "$i" | grep -v '{}' | xargs git push origin ; done

Deleted tag '2013-01-01' (was 9222414)
Deleted tag '2013-01-01.0' (was f369094)
Deleted tag '2013-01-04' (was dd5c87d)
Deleted tag '2013-01-09' (was 699777a)
(snipped)
To anavarre@myhosting.com:anavarre.git
 - [deleted]         2013-01-01
 - [deleted]         2013-01-01.0
 - [deleted]         2013-01-04
 - [deleted]         2013-01-09
(snipped)

Note a few things:

  • To see your existing tags locally, simply run git tag -l
  • To see your existing tags remotely, use the git ls-remote --tags origin command
  • xargs is used to build and execute command lines from standard input
  • awk and grep are used to slightly modify the output and work with remote tags more easily
  • Be extra careful before running the above command as it could potentially cause great troubles to your development team and production site(s).

Tags
Git

Date
January 7, 2014