4

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?

2
  • 2
    I think you need to double the percent to escape it for %H and then again because its in a batch file. Commented May 3, 2016 at 12:55
  • That and escaping the = was the ticket. Commented May 3, 2016 at 14:16

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

You sir, are a legend. I finally got it working with git log --pretty^=format:"%%H" -n 1 so it turns out it was the equals sign and a missing extra %
0

Why not run:

git rev-parse --verify HEAD

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.