This is what I like to use.
Code:
$ # linux tree at tagged release
$ cd /usr/src/linux
$ version=$( git describe 2>/dev/null || git rev-parse HEAD 2>/dev/null || echo 'unknown' )
$ echo $version
v5.1.15
$
$ # My personal dwm branch, 8 commits past tagged release
$ cd ~/projects/dwm/
$ version=$( git describe 2>/dev/null || git rev-parse HEAD 2>/dev/null || echo 'unknown' )
$ echo $version
6.0.2-8-g2f4bc6b
$
$ # Another project of mine with no tags as yet
$ cd ../xtc
$ version=$( git describe 2>/dev/null || git rev-parse HEAD 2>/dev/null || echo 'unknown' )
$ echo $version
a80500cda681caf5854e9e31cab4d0f8dce0b645
$
You can also add '--short' to git rev-parse if you don't want the full ref, and the '--long' option of git describe will force it to always include the number of commits since the last tag, and the ref, even when HEAD is at that tag.