Operations 3 min read

Automatically Tag Commits on Git Push with a Shell Script

This article provides a shell script and step‑by‑step instructions for configuring a Git pre‑push hook that automatically generates and pushes a new semantic version tag each time code is pushed to the remote repository.

ZhiKe AI
ZhiKe AI
ZhiKe AI
Automatically Tag Commits on Git Push with a Shell Script

Git pre‑push hook for automatic version tagging

The script determines the most recent tag, falls back to v1.0.0 if none exists, parses the major, minor and patch components, increments the appropriate component (rolling over at 100), assembles a new tag, and creates an annotated tag.

#!/bin/sh
git pull
# Get the most recent tag; fall back to v1.0.0 if none exists
tag=$(git describe --tags `git rev-list --tags --max-count=1`)
if [ $? -ne 0 ]; then
    tag='v1.0.0'
fi

echo "current tag is $tag"

# Split the tag into major, minor, and patch components
lastTag=${tag##*.}
echo "last tag is $lastTag"

tempTag=${tag#*.}
midTag=${tempTag%.*}
echo "middle tag is $midTag"

tempTag=${tag:1}
higTag=${tempTag%%.*}
echo "high tag is $higTag"

# Increment the appropriate component, rolling over at 100
i=$(( $lastTag + 1 ))
if [ $i -gt 100 ]; then
    lastTag=0
    i=$(( $midTag + 1 ))
    if [ $i -gt 100 ]; then
        midTag=0
        let "higTag+=1"
    else
        let "midTag+=1"
    fi
else
    let "lastTag+=1"
fi

# Assemble the new tag and create it
newTag=${tag:0:1}${higTag}.${midTag}.${lastTag}
echo $newTag
git tag -a $newTag -m "new tag $newTag"

Place the script in .git/hooks and rename pre-push.sample to pre-push. Ensure the file is executable.

When a push is performed, Git runs the pre‑push hook, generates the next tag, and creates the annotated tag locally. To push the new tag to the remote, the client must have the “push tags” option enabled.

Git hooks directory
Git hooks directory
Push dialog with tag option
Push dialog with tag option
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GitVersion Controlshell scriptautomatic taggingpre-push hook
ZhiKe AI
Written by

ZhiKe AI

We dissect AI-era technologies, tools, and trends with a hardcore perspective. Focused on large models, agents, MCP, function calling, and hands‑on AI development. No fluff, no hype—only actionable insights, source code, and practical ideas. Get a daily dose of intelligence to simplify tech and make efficiency tangible.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.