Is it possible to retrieve a git tag from within MATLAB?
10 views (last 30 days)
Show older comments
I am developing a set of code to process data, simulate a model, and plot figures. I'm using Git for version control via the Git bash and periodically tagging the code to keep a record of key development points.
At these key development points I am also using the code to construct preliminary data files (.mat) and figures and I need to keep track of which code version (git tag) was used to create the files/figures.
Is there a way to extract the current git tag from within MATLAB?
I've been manually updating a variable within my code to indicate the version, but I've recently begun using development branches in Git and keeping up with manually updating a hardcoded variable when switching between git branches is no longer effective.
0 Comments
Accepted Answer
Ruchika Parag
on 14 Jul 2025
Hi @Laura, you can absolutely extract the current Git tag (or commit ID) from within MATLAB, which is very useful for tracking which version of your code generated a specific figure or data file.
There are two common ways to do this:
1. Use the Git Command Line from MATLAB
If you're already using Git from the terminal, you can call Git commands directly from MATLAB using system():
[~, tagString] = system('git describe --tags --first-parent --abbrev=7 --long --dirty --always');
tagString = strtrim(tagString);
This gives you something like v1.2.3-4-g123abc, which represents the latest tag, number of commits since that tag, and the short hash. You can include this in your .mat files or figure metadata.
2. Use MATLAB’s Git API (R2023b or newer)
MATLAB now includes a Git interface via the gitrepo object:
repo = gitrepo;
commitID = repo.LastCommit.ID;
This gives you the current commit hash. You won’t get the human-readable tag directly, but it’s still helpful for tracking.
Suggested Workflow
You can combine both methods to fall back gracefully if the Git API isn't available:
try
repo = gitrepo;
versionInfo = repo.LastCommit.ID;
catch
[~, versionInfo] = system('git describe --tags --first-parent --abbrev=7 --long --dirty --always');
versionInfo = strtrim(versionInfo);
end
disp(['Code version: ', versionInfo]);
This way, your scripts always record which version of the code produced the output—without needing to manually update anything when switching branches or tags.
Hope this helps!
More Answers (0)
See Also
Categories
Find more on Source Control in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!