I want to use git command git show -s --format=%h
in batch file, want to store the result in variable.
This doesn't work:
FOR /F %%i IN ('git show -s --format=%h') DO set commit=%%i
echo commit=%commit%
because with echo on
the command it executes is:
FOR /F %i IN ('git show -s --format') DO set commit=%i
and output is:
commit=
This method works, but seems odd solution:
set hhh="=%%h"
FOR /F %%i IN ('git show -s --format%hhh%') DO set commit=%%i
because the command executes is:
FOR /F %i IN ('git show -s --format"=%h"') DO set commit=%i
and output is correct:
commit=6446e53
I guess it it related to how variables are referenced and used in batch file with percent sign.
Is there a better solution, that will execute as it should: git show -s --format=%h
?
CodePudding user response:
Here is a list of how to escape characters in batch files: Escape Characters - by Rob van der Woude
In case the link goes down in the future:
Character to be escaped | Escape Sequence | Remark |
---|---|---|
% | %% | |
^ | ^^ | May not always be required in doublequoted strings, but it won't hurt |
& | ^& | |
< | ^< | |
> | ^> | |
| | ^| | |
' | ^' | Required only in the FOR /F "subject" (i.e. between the parenthesis), unless backq is used |
` | ^` | Required only in the FOR /F "subject" (i.e. between the parenthesis), if backq is used |
, | ^, | Required only in the FOR /F "subject" (i.e. between the parenthesis), even in doublequoted strings |
; | ^; | |
= | ^= | |
( | ^( | |
) | ^) | |
! | ^^! | Required only when delayed variable expansion is active |
" | "" | Required only inside the search pattern of FIND |
\ | \\ | Required only inside the regex pattern of FINDSTR |
[ | \[ | |
] | \] | |
" | \" | |
. | \. | |
* | \* | |
? | \? |