Skip to content

Instantly share code, notes, and snippets.

@rotated8
Created May 23, 2023 20:13
Show Gist options
  • Save rotated8/e27905c2ea28eec379add7d385cfd525 to your computer and use it in GitHub Desktop.
Save rotated8/e27905c2ea28eec379add7d385cfd525 to your computer and use it in GitHub Desktop.
Get the tag for a commit, or the branch@hash. Useful for showing a version.
#!/usr/bin/env bash
# Set repo_dir to folder this script lives in.
repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
if [[ $# -eq 1 && -n "$1" && -d "$1" ]]; then
# Script was called with an argument that is a path to a directory.
repo_dir="$1"
fi
# Get tags for HEAD.
tag=$( git -C "${repo_dir}" tag --no-color --contains )
if [[ -z "${tag}" ]]; then
# No tag, get branch and short commit hash.
branch=$( git -C "${repo_dir}" branch --no-color --show-current )
hash=$( git -C "${repo_dir}" log --no-color --max-count=1 --pretty='format:%h' )
tag="${branch}@${hash}"
fi
echo "${tag}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment