# How to include part of an external git hash as text inside a document?

This is my first time asking a question on a site like this. Please tell me if I should do something differently, thanks!

I want to include a short version of the latest commit hash from git as a text string in a (Xe)LaTeX document. How do I do that?

I am able to include the full hash simply with:

\input{.git/ORIG_HEAD}


But I am not able to figure out how to shorten down the hash with the xstring package when I am getting the string from a macro. What I currently have is this:

\usepackage{xstring}

I would prefer \gitrevision\ to be a short hash.


A fix for the above code would be most appreciated, as the code is constructed from my way of thinking. Yes, I have RTFM, but it is in my opinion lacking in the department of plain down-to-earth usage examples.

Of course, a completely different (working) solution is also welcome!

A final note, I would easily be able to do all this with an external bash script and/or with the \write18 macro, but I have put an arbitrary limit on myself to only rely on TeX in this case. Otherwise I will never learn more. Many thanks for taking the time to read this question!

• Not exactly answering your question, but have you seen the gitinfo package? – Torbjørn T. Nov 2 '13 at 22:02
• Yes, with gitinfo I can get the desired result. But I would like to set up a workflow where scripts (git hooks included) aren’t needed. And it seems to me that the xstring solution should work, just that I am missing some crucial understanding of TeX’s grammar or inner workings. – Kess Vargavind Nov 3 '13 at 4:00

The more general solution to including git metadata in documents is the gitinfo2 package (which supersedes gitinfo that I mentioned in a comment). Having set that up, \gitAbbrevHash gives you a seven character hash.

There may be more elegant ways of achieving this, but as a workaround you can use the catchfile package to store the full hash in a macro, and use this macro in \StrLeft.

\documentclass{article}
\usepackage{xstring}
\usepackage{catchfile}
\newcommand{\gitrevision}{%

• On Windows \CatchFileDef seem neither to work with files without extensions (like master) nor relative paths beginning with . (like the .git folder). Is there an alternative to \CatchFileDef whose file path input is more permissive? – alx9r Jul 8 '17 at 21:53