How do I get the output from a call to GIT into a variable in a batch script?

batch-file, git, windows

Solution

I don't have a Windows system handy to test, but I think something along these lines:

FOR /F %i IN (`git log --pretty=format:"%%H" -n 1`) DO SET CURRENT_SHA=%i

Note that the "%H" needs to be escaped, but to use this line in a batch file you also need to double escape everything. You may also need to escape the double-quotes with `^`. I think this ought to work:

SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=* USEBACKQ" %%a in (`git log --pretty^=format:"%%H" -n 1`) do (SET CURRENT_SHA=%%a)
ECHO Current Sha: %CURRENT_SHA%

But really, if you want to do shell programming in Windows just use Powershell and then you can do:

$CURRENT_SHA=git log --pretty=format:"%H" -n 1

Problem

I have a git command to get the latest SHA of the current repo as follows: ``` git log --pretty=format:"%H" -n 1 ``` I have a windows batch script I'd like to use this in as follows: ``` SET CURRENT_SHA=??? ``` But I'm at a loss as to how to get the output from that call to git into the variable so that I can make use of it. Edit I've tried the following (which seems to be the general advice I've read here and elsewhere): ``` SETLOCAL ENABLEDELAYEDEXPANSION FOR /F "tokens=* USEBACKQ" %%i IN (`git log --pretty=format:"%H" -n 1`) DO (SET CURRENT_SHA=%%i) ECHO Current Sha: %CURRENT_SHA% ``` ..but I get: ``` fatal: failed to stat 'format:i) ECHO Current Sha: 48bce83e800b96607afb2a387c4fcd7b0b0f037e ``` So presumably there's a problem with the quotes?

Original source